Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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",
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!