Skip to content
Advertisement

Is there any way to use Jest and jest-dom together without having to transpile?

I want to write a unit test with Jest, with jest-dom as a mock DOM–without having to transpile. I was hoping all I had to do was import the jest-dom package with a CommonJS import. But when I do that, then run my tests (with npm test), it still fails with:

ReferenceError: document is not defined (full output here)

Any ideas how to resolve this? My test file is below.

Thanks.


My Code

myApp.test.js

require("@testing-library/jest-dom");
document.createElement("div");

Advertisement

Answer

After some trial and error, I got it working. Here were the edits I made:

myApp.test.js (test file)

require("@testing-library/jest-dom/extend-expect");

I saw there in this post.

package.json Add the following to top level:

  "jest": {
    "testEnvironment": "jest-environment-jsdom"
  },

I did that b/c this doc page said I should edit my Jest testEnvironment to jest-environment-jsdom. I don’t know why that string is used as the value, instead of the name of the package (test-dom). But this is what’s working for me.

This doc page shows how to edit my Jest testEnvironment.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement