document object doesn't work properly in test with jest jsdom

Viewed 263

I am using jest with jsdom to test my application.

/**
 * @jest-environment jsdom
 */
const html = fs.readFileSync(
  path.resolve(__dirname, "../public/index.html"),
  "utf8"
);
let dom;
let doc;
let container;

describe("index.html", () => {
  beforeEach(() => {
    dom = new JSDOM(html);
    doc = dom.window.document;
    container = doc.body;
    dom.window.fetch = fetch;
    window.fetch = fetch;
  });

  it("renders elements", () => {
    new Form(container.querySelector("#app"));
  });

});

inside the Form.js file I use document to create and append element

class Form {
  parentElement: HTMLDivElement;
  localRootElement: HTMLFormElement;
  constructor(parent: HTMLElement) {
    this.parentElement = parent as HTMLDivElement;
    const formEl = document.createElement("form")! as HTMLFormElement;
    this.localRootElement = formEl;
    this.render()
  }

  private render = (): void => {
    this.parentElement.appendChild(this.localRootElement);
  };

and I got error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

It seems that document comes from jsdom works ok because this.parentElement accurately has appendChild method attached to it. However the form element created by document object can not be appended because it says it is not of type 'Node'. I did console.log(document) that gave me Document { location: [Getter/Setter] }(No wonder why that didn't work)

My question is

Could I somehow assign jsdom.window.document to document object to do things like createElement properly?

Or is there a good alternative?

installed version

 "jest": "^27.5.1",
 "@testing-library/dom": "^8.11.3",
 "@testing-library/jest-dom": "^5.16.2",
0 Answers
Related