我正在使用 create-react-app。从 CLI 运行 jest
会导致此错误(尽管在 VS Code 中它在我的测试文件中显示我的测试通过):
(base) ➜ component-library git:(setup) ✗ jest
FAIL src/App.test.js
● Test suite failed to run
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:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• 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:
/Users/Me/go/src/gitlab.com/tensile-payments/component-library/src/setupTests.js:5
import '@testing-library/jest-dom';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
我的 setupTests.js 文件如下所示:
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
import Enzyme from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
Enzyme.configure({ adapter: new Adapter() });
我从另一个问题的 answer 中了解到,在运行测试之前,Jest Babel 会转换文件,这应该去掉这些导入语句。我没有弹出,所以没有更改 babel 配置。其他人遇到的问题是节点模块没有被转换,因为默认配置排除了它们,但这个错误不是来自节点模块。我该如何解决这个问题?
答案 0 :(得分:0)
我通过使用 npm run test
而不是 jest
运行测试以及删除
"jest": {
"setupFilesAfterEnv": [
"<rootDir>src/setupTests.js"
]
}
来自我的 package.json
(虽然 Enzyme instructs 在使用 Jest 时包含它)。