[英]When testing react project npm test works but jest doesn't
我已經使用create-react-app創建了一個新的react應用,並添加了幾個簡單的組件和測試。 使用“ npm test”運行測試時,它們運行良好。 當開玩笑地運行時,在測試中使用導入的組件時會得到“意外令牌”。 例如:
import React from 'react';
import { shallow } from 'enzyme';
import App from './App';
it('renders without crashing', () => {
shallow(<App />);
});
測試中使用App會產生錯誤,但僅在運行笑話時會出現錯誤。
unexpected token
錯誤很可能是因為您尚未安裝babel-jest
,也未將transform
密鑰添加到jest.json
。 我希望createReactApp is doing something to hide this from you. If you want to use non-createReactApp commands (like
is doing something to hide this from you. If you want to use non-createReactApp commands (like
jest`),那么我會“ 彈出 ”該應用程序(無法撤消),以便可以看到所有配置等。
或者您可以添加自己的jest.json,但是我覺得使用2種運行測試的方法可能會造成混淆。
如果您想對此進行更多控制,建議您使用create-react-app
繞開開箱即用的內容。
您可以在package.json
中添加一個test
條目,該條目實際上將使用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
執行測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.