我该如何修复 React 应用程序中的这个 Jest 错误?
2020-06-20
754
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:
• 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:
SyntaxError: /home/edi/web-dev/OnlineMarket/client/src/css/Home.css: Unexpected token (1:0)
> 1 | .home-wr {
| ^
2 | position: relative;
3 | width: 80%;
4 | margin: 30px 10%;
at Parser._raise (node_modules/@babel/parser/src/parser/error.js:60:45)
at Parser.raiseWithData (node_modules/@babel/parser/src/parser/error.js:55:17)
at Parser.raise (node_modules/@babel/parser/src/parser/error.js:39:17)
at Parser.unexpected (node_modules/@babel/parser/src/parser/util.js:149:16)
at Parser.parseExprAtom (node_modules/@babel/parser/src/parser/expression.js:1174:20)
at Parser.parseExprSubscripts (node_modules/@babel/parser/src/parser/expression.js:541:23)
at Parser.parseMaybeUnary (node_modules/@babel/parser/src/parser/expression.js:521:21)
at Parser.parseExprOps (node_modules/@babel/parser/src/parser/expression.js:312:23)
at Parser.parseMaybeConditional (node_modules/@babel/parser/src/parser/expression.js:264:23)
at Parser.parseMaybeAssign (node_modules/@babel/parser/src/parser/expression.js
这是我在只有一个测试的情况下运行“npm test”时遇到的错误:
import React from 'react'
import ReactDOM from 'react-dom'
import App from '../src/App'
it('should render app', () => {
let div = document.createElement('div')
ReactDOM.render(<App />, div)
ReactDOM.unmountComponentAtNode(div)
})
此外,此 React 应用程序位于我包含 node.js 应用程序的文件夹中: -client(包含 React 应用程序的文件夹) . . index.js(node.js 应用程序) package.json
我提到这一点是因为当我第一次为 node.js 应用程序安装 Jest 时,React 抛出一个错误,告诉我这是 jest-babel 版本的问题或类似的东西。我不知道这是否与此有关。此外,node.js 应用程序的测试运行良好。
1个回答
您可以在这里找到完整的答案: https://stackoverflow.com/a/54646930/406110
但基本上,jest 不知道如何解释 CSS 导入 - 您需要使用样式模拟 - 因为您可能不需要在任何 jest 测试中使用样式。
// jest.config.js
module.exports = {
moduleNameMapper: {
'\\.(css)$': '<rootDir>/test/jest/__mocks__/styleMock.js',
}
};
// test/jest/__mocks__/style-mock.js
module.exports = {};
在您的 jest.config.js 文件中使用此代码将使导入返回一个空对象给 javascript,而不会破坏尝试将 CSS 代码转换为 javascript 的转译。
richardaum
2020-06-20