Monday, July 4, 2022

How to fix " ReferenceError: document is not defined" in Jest?

When I setup a test again the AppShell in Micro-Frontend Application Development, then I added the test command to the scripts section in the package.json 

   "test": "jest"

now the scripts section should be shown as below.

 "scripts": {
    "dev": "tsc --watch --outDir dist",
    "build": "tsc --outDir dist",
    "lint": "eslint *.ts*",
    "storybook": "start-storybook",
    "test": "jest"
  },


However when i run the test with pnpm test, I encoutered the error in the following image.







"AppShell › renders

    The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string.

    Consider using the "jsdom" test environment."


based on the suggestion, i added the environment tag jsdom to the test command, then the test run is succeed.

"scripts": {
    "dev": "tsc --watch --outDir dist",
    "build": "tsc --outDir dist",
    "lint": "eslint *.ts*",
    "storybook": "start-storybook",
    "test": "jest --env=jsdom"
  },

The successful test run is shown below.





No comments:

Post a Comment