Search code examples
vitest

Migration from Jest to Vitest got error "ReferenceError: DOMParser is not defined"


I migrated my test from Jest to Vitest, when I run the test, I got following error:

stderr | tests/unit/parsers/XMLParserPlugin.spec.ts > parse Compacted
ReferenceError: DOMParser is not defined
    at XMLParserPlugin.parse (/Users/jianwu.chen/opensource/TreedocViewer/src/parsers/XMLParserPlugin.ts:26:19)
    at /Users/jianwu.chen/opensource/TreedocViewer/tests/unit/parsers/XMLParserPlugin.spec.ts:13:25
    at /Users/jianwu.chen/opensource/TreedocViewer/node_modules/vitest/dist/chunk-runtime-chain.0ab05798.mjs:2266:13
 

Solution

  • After some research, I solved this issue by adding following annotation to the test the depends on DOMParser.

    /**
     * @vitest-environment jsdom
     */
    

    Also need to run:

    yarn add jsdom
    

    Reference: https://dev.to/mbarzeev/from-jest-to-vitest-migration-and-benchmark-23pl