tldr
npm install jest --save-dev
(不确定是否需要--我只是这样做了)。
- 替换
"scripts": {
...
"test": "react-scripts test",
...
},
随着
"scripts": {
...
"test": "jest --watch",
...
},
一切
对我来说,添加 -- --config=jest.config.js
似乎有所作用:我的测试通过了,但随后我收到了以下错误信息(被截断):
一切
对我来说,添加-- --config=jest.config.js
似乎有一定作用:我的测试通过了,但是随后我遇到了以下错误(被截断):
Invalid testPattern --config=jest.config.js|--watch|--config|{"roots":["<rootDir>/src"]
...
Running all tests instead.
这个问题在上面的评论中有提到。
以下是发生的事情:
npm test
会查找package.json中scripts.test
的内容并运行它。对于create-react-app,这是react-scripts test
。接着,它会运行/node_modules/react-scripts/scripts/test.js
(源代码)来构建一个基于你的环境的jest配置。当你添加:
"test": "react-scripts test -- --config=jest.config.js",
对于package.json
,它替代了react-scripts test
试图创建的jest配置(好!),但它也篡改了"test": "react-scripts test"
生成的参数(坏!),因此jest认为您正在尝试传递一个测试模式(这显然不是一个有效的测试模式)。
因此,我决定尝试使用jest CLI运行我的测试。至少对我来说,它能很好地运行并且捕获了所有的测试。它自动查找jest.config.js
,所以它可以正常工作,并且您可以传递--watch
,以获得与react-scripts test
相同的行为。
请记住,react-scripts test
似乎要经过很多麻烦来构建一个“合适”的配置;我肯定没有尝试解决所有这些问题:可能会有不同的结果。以下是它在我的环境中创建的完整选项集。例如,对于--config
,数组中的下一个元素就是配置文件。
[
'--watch',
'--config',
'{"roots":["<rootDir>/src"],
"collectCoverageFrom":["src/**/*.{js,jsx,ts,tsx}",
"!src/**/*.d.ts"],
"setupFiles":["<my_root_elided>/node_modules/react-app-polyfill/jsdom.js"],
"setupFilesAfterEnv":["<rootDir>/src/setupTests.js"],
"testMatch":["<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
"<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"],
"testEnvironment":"jsdom",
"testRunner":"<my_root_elided>/node_modules/jest-circus/runner.js",
"transform":{
"^.+\\\\.(js|jsx|mjs|cjs|ts|tsx)$":"<my_root_elided>/node_modules/react-scripts/config/jest/babelTransform.js",
"^.+\\\\.css$":"<my_root_elided>/node_modules/react-scripts/config/jest/cssTransform.js",
"^(?!.*\\\\.(js|jsx|mjs|cjs|ts|tsx|css|json)$)":"<my_root_elided>/node_modules/react-scripts/config/jest/fileTransform.js"},
"transformIgnorePatterns":["[/\\\\\\\\]node_modules[/\\\\\\\\].+\\\\.(js|jsx|mjs|cjs|ts|tsx)$",
"^.+\\\\.module\\\\.(css|sass|scss)$"],
"modulePaths":[],
"moduleNameMapper":{"^react-native$":"react-native-web",
"^.+\\\\.module\\\\.(css|sass|scss)$":"identity-obj-proxy"},
"moduleFileExtensions":["web.js", "js", "web.ts", "ts", "web.tsx", "tsx", "json", "web.jsx", "jsx", "node"],
"watchPlugins":["jest-watch-typeahead/filename", "jest-watch-typeahead/testname"],
"resetMocks":true,
"rootDir":"<my_root_elided>"}',
'--env',
'<my_root_elided>/node_modules/jest-environment-jsdom/build/index.js'
]