我使用create-react-app来创建一个新的反应应用程序,并添加了几个简单的组件和测试。使用'npm test'运行测试时,运行正常。当使用jest运行时,在测试中使用导入的组件时,我会得到“意外的令牌”。例如:
import React from 'react';
import { shallow } from 'enzyme';
import App from './App';
it('renders without crashing', () => {
shallow(<App />);
});
在测试中使用App会产生错误,但仅限于运行jest时。
unexpected token
错误可能是因为你没有安装babel-jest
并且没有将transform
密钥添加到jest.json
。我希望createReactAppis doing something to hide this from you. If you want to use non-createReactApp commands (like
jest`)然后我''eject'应用程序(无法撤消),以便您可以看到所有配置等。
或者你可以添加自己的jest.json,但我觉得这有两种运行测试的方法可能会让人感到困惑。
如果你想要更多地控制它,我建议绕过create-react-app
开箱即用的东西。
您可以在test
中添加package.json
条目,该条目主要使用jest
,但允许您传递配置文件。
"scripts": {
...
"test": "jest --config jest.conf.js",
...
},
然后在jest.conf.js
中,您可以添加要在测试中使用的变量。 collectCoverage
和coverageDirectory
属性用于代码覆盖。
{
"globals":{
"__DEV__": true,
"API_BASE_URL": "http://api",
"SOME_VAR": "whatever"
"unmockedModulePathPatterns": [
"node_modules/react/",
"node_modules/enzyme/"
]
},
"collectCoverage": "true",
"coverageDirectory": "coverage"
}
然后在运行npm run test
时,它将使用jest
执行测试,并使用自定义配置。