简体   繁体   English

如何在 create-react-app 中使用 jest.config.js

[英]How to use jest.config.js with create-react-app

I would like to move my jest config out of my package.json, i am trying to use the --config as suggested here but get the error argv.config.match is not a function我想将我的 jest 配置移出我的 package.json,我正在尝试按照此处的建议使用 --config 但得到错误argv.config.match is not a function

package.json包.json

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --config jest.config.js",
    "eject": "react-scripts eject",
  },

cli命令行

hutber@hutber-mac:/var/www/management/node$ npm test -u

> management-fresh@0.1.0 test /var/www/management/node
> react-scripts test --config jest.config.js

Usage: test.js [--config=<pathToConfigFile>] [TestPathPattern]


argv.config.match is not a function
npm ERR! Test failed.  See above for more details.

For me appending -- --config=jest.config.js worked.对我来说,附加-- --config=jest.config.js有效。

So the whole string react-scripts test -- --config jest.config.js in your case.所以整个字符串react-scripts test -- --config jest.config.js在你的情况下。

TL;DR TL; 博士

Add -- before your options.在您的选项之前添加--

"test": "react-scripts test -- --config=jest.config.js",

The problem here is with react-scripts not seeing the options being passed to it.这里的问题是react-scripts没有看到传递给它的选项。 We can demonstrate this by running it directly.我们可以通过直接运行来证明这一点。

./node_modules/.bin/react-scripts test --config=jest.config.js
# argv.config.match is not a function

./node_modules/.bin/react-scripts test -- --config=jest.config.js
# This works.

Variations变化

How you pass options to scripts varies depending on which versions of npm or Yarn you use.将选项传递给脚本的方式因您使用的npmYarn版本而异。 For completeness, here are the results for the variations:为完整起见,以下是变体的结果:

# This runs, but completely ignores the option.
npm test --config=jest.config.js

# These result in "argv.config.match is not a function," indicating that the
# options were not understood.
npm test -- --config=jest.config.js
yarn test -- --config=jest.config.js
yarn test --config=jest.config.js

create react app sets up the test script in package.json with create react apppackage.json设置测试脚本

"test": "react-scripts test",

You can set additional options like so.您可以像这样设置其他选项。

"test": "react-scripts test -- --config=jest.config.js",

Something like this might work if you want to send options through the CLI.如果您想通过 CLI 发送选项,这样的事情可能会起作用。

"test": "react-scripts test --",
yarn test --bail
# comes through as
react-scripts test -- --bail

Resources资源

Here are a few resources to explain the different usage.这里有一些资源来解释不同的用法。

For me adding jest as key in package.json file worked.对我来说,在package.json文件中添加jest作为关键。 Added all the required config as object in jest key rather than jest.config.jsjest键而不是 jest.config.js 中添加了所有必需的配置作为对象

"jest": {
    "collectCoverageFrom": [
      "src/**/*.js",
      "!**/node_modules/**"
    ],
    "coverageReporters": [
      "text-summary",
      "lcov",
      "cobertura"
    ],
    "testMatch": [
      "**/*.test.js"
    ]
  },

tldr域名

  • npm install jest --save-dev (not sure if this is required -- I just did it). npm install jest --save-dev (不确定是否需npm install jest --save-dev ——我刚刚做到了)。
  • replace代替
"scripts": {
    ...
    "test": "react-scripts test",
    ...
  },

with

"scripts": {
    ...
    "test": "jest --watch",
    ...
  },
  • run tests as normal with npm test使用npm test正常npm test

Everything一切

Adding -- --config=jest.config.js sort of work for me: my tests passed, but then I was getting the following error (truncated):添加-- --config=jest.config.js对我来说有点工作:我的测试通过了,但随后出现以下错误(被截断):

Invalid testPattern --config=jest.config.js|--watch|--config|{"roots":["<rootDir>/src"]
...
Running all tests instead.

This problem is noted in the comment above . 上面评论中指出了这个问题。

Here's what's going on:这是发生了什么:

npm test looks in package.json for whatever is in scripts.test and runs that. npm test在 package.json 中scripts.test任何scripts.test并运行它。 For create-react-app, that's react-scripts test .对于 create-react-app,就是react-scripts test This, in turn, runs /node_modules/react-scripts/scripts/test.js ( source ) (you can easily print debug this to see what's going on).这反过来又运行/node_modules/react-scripts/scripts/test.js ( source )(您可以轻松打印 debug this 以查看发生了什么)。 This script builds up a jest configuration based on your environment.此脚本会根据您的环境构建一个 jest 配置。 When you add:添加时:

"test": "react-scripts test -- --config=jest.config.js",

to package.json , this replaces the jest config that react-scripts test is trying to create (yea!), but it also munges the arguments that "test": "react-scripts test" generates (boo!), so jest thinks you're trying to pass in a test pattern (which is obviously not a valid test pattern).package.json ,这替换了react-scripts test试图创建的 jest 配置(是的!),但它也修改了"test": "react-scripts test"生成的参数(嘘!),所以 jest 认为您正在尝试传入测试模式(这显然不是有效的测试模式)。

So, I decided to try running my tests using the jest CLI.所以,我决定尝试使用 jest CLI 运行我的测试。 At least for me, it worked fine and picked up all of my tests.至少对我来说,它运行良好并完成了我所有的测试。 It automatically looks for jest.config.js , so that works, and you can pass --watch in to get the same behavior as react-scripts test .它会自动查找jest.config.js ,这样就可以了,您可以传入--watch以获得与react-scripts test相同的行为。

Keep in mind that react-scripts test seems to be going through a lot of trouble to build up a 'proper' config;请记住, react-scripts test似乎在构建“正确”配置方面遇到了很多麻烦; I definitely haven't tried to figure all of that out: YMMV.我绝对没有试图弄清楚所有这些:YMMV。 Here's the full set of options it creates in my env.这是它在我的环境中创建的全套选项。 Eg, for --config the next element in the array is the config.例如,对于--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'
]

I would try adding "test": "jest --no-cache -w 2" to your package.json.我会尝试将"test": "jest --no-cache -w 2"到你的 package.json 中。 Then run npm run test然后运行npm run test

This one got me too!这个也给我了! create react app is a bit tricky as it already contains jest. create react app 有点棘手,因为它已经包含了笑话。 I removed the --config jest.config.js line, and didn't need that extra test.config file.我删除了--config jest.config.js行,并且不需要那个额外的 test.config 文件。

I also made sure my enzyme file was named setupTests.js.我还确保我的酶文件被命名为 setupTests.js。 The testing module will be specifically looking to run that file, so it must be named that.测试模块将专门寻找运行该文件,因此它必须命名为。 Also,I had to have it in my src/ folder, where before I had it in a src/test folder.另外,我必须将它放在我的 src/ 文件夹中,而之前我将它放在 src/test 文件夹中。 If you are asking the above question you are probably past this point, but wanted to mention just in case.如果您问上述问题,您可能已经过了这一点,但还是想提一下以防万一。 My setupTests.js looks like:我的 setupTests.js 看起来像:

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({
  adapter: new Adapter()
})

For me, none of the above answers worked.对我来说,以上答案都没有奏效。 But with the help of documentation, I found out the way around.但是在文档的帮助下,我找到了解决方法。 For this purpose, place the code you want to configure jest, in your_project_root_folder/src/setupTests.js .为此,将要配置 jest 的代码放在your_project_root_folder/src/setupTests.js My your_project_root_folder/src/setupTests.js looks like this我的your_project_root_folder/src/setupTests.js看起来像这样

import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'

Enzyme.configure({
    adapter: new Adapter(),
})

And one more important point, you need to use enzyme-adapter-react-16 for react v16 and enzyme-adapter-react-15 for react v15还有一个更重要的一点,你需要使用enzyme-adapter-react-16react v16enzyme-adapter-react-15 react v15

Moreover, if you want to use enzyme-to-json , you can place the following code in package.json file此外,如果你想使用enzyme-to-json ,你可以在package.json文件中放置以下代码

  "jest": {
    "snapshotSerializers": ["enzyme-to-json/serializer"]
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用不同的 jest.config.js 进行单元和组件测试? - How to use different jest.config.js for unit and component tests? 在 TypeScript 中使用 NextJS 设置 Jest + React 测试库 — 设置 upp jest.config.js 时出错 - Setup Jest + React testing library using NextJS in TypeScript — error setting upp jest.config.js 带有 Mono Repo 的 react-scripts 的无效 testPattern --config=jest.config.js - Invalid testPattern --config=jest.config.js with react-scripts with Mono Repo 如何使用create-react-app设置Jest Watch插件 - How to setup Jest Watch Plugins with create-react-app 创建反应应用程序测试和笑话模拟 - Create-React-App Testing and Jest Mocking 在 jest.config.js 文件中导入本地文件 - Importing local files in `jest.config.js` file jest.config.js 中的`moduleNameMapper` 设置不适用于 CircleCI - `moduleNameMapper` settings in jest.config.js doesn't work on CircleCI 如何在create-react-app中使用引导程序? - How to use bootstrap in create-react-app? jest.config.js 失败 - 意外的标记“。” 在 module.exports 中 - jest.config.js fails - unexpected token '.' in module.exports 尝试将 jest 与 create-react-app 和 typescript 一起使用。 获取错误:开玩笑:无法解析 TypeScript 配置文件...找不到模块“ts-node” - Trying to use jest with create-react-app and typescript. Get error: Jest: Failed to parse the TypeScript config file... Cannot find module 'ts-node'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM