【发布时间】:2021-07-17 05:07:14
【问题描述】:
我正在使用 Jest 向现有代码库添加测试。这是我得到的错误
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/home/me/app/node_modules/register-service-worker/index.js:32
export function register (swUrl, hooks) {
^^^^^^
SyntaxError: Unexpected token export
我不明白如何正确配置transformIgnorePatterns?
但是我的 jest.config.js 设置为忽略 node_modules ?
查看react example,但无法真正理解它如何转化为我的东西......?我在 VueJS 项目中,没有使用 typescript。
module.exports = {
preset: "@vue/cli-plugin-unit-jest/presets/typescript-and-babel",
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1",
},
transformIgnorePatterns: ["/node_modules/"],
// setupFiles: [
// "./tests/unit/setup.ts",
// ],
};
【问题讨论】:
-
我的建议是,为
register-service-worker创建一个mock。无论如何,您不应该真正测试 3rd 方代码 -
你见过this
-
@Phil - OP 没有尝试测试第三方代码,他们想知道为什么
node_modules没有被忽略。为该服务人员创建一个模拟只会导致node_modules中的其他内容试图被转译。 -
@Adam 我的意思是第 3 方代码包含在测试中,这是您无法控制的。 IMO,应控制合作者
-
@Adam 不幸的是,链接的建议没有帮助。同样的错误。我会尝试模拟它,因为无论如何我都需要学习...但是如果有人知道如何阻止 Jest 调查
node_modules在我的情况下,请告诉我。谢谢:)
标签: javascript node.js vue.js jestjs