如何让 jest 使用与 create-react-app 上的 react-script 测试相同的配置运行? [英] How can I make jest run with the same config as react-script test on a create-react-app?

查看:24
本文介绍了如何让 jest 使用与 create-react-app 上的 react-script 测试相同的配置运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以运行 npm test 它运行 react-script test 并且它可以工作,它成功地运行了测试.但我有兴趣弄清楚如何使用 react-script 使用的相同配置直接运行 jest.希望不必复制配置或弹出应用程序.我开始阅读 react-scripts 的源代码,但到目前为止我无法弄清楚.

I know I can run npm test which runs react-script test and it works, it successfully run the tests. But I'm interested in figuring out how to run jest directly with the same configuration react-script uses. Hopefully without having to replicate the configuration or ejecting the app. I started reading the source code of react-scripts but so far I couldn't figure it out.

想要这个的原因是:

  • 我的 CRA 项目是一个更大项目的一部分,我可以在顶层运行 jest 并运行所有测试.
  • 在 WebStorm 中,我可以利用 Jest 集成,其中包括:
    • 显示运行时通过或失败的测试列表.
    • 能够运行单独的测试.
    • 进行代码覆盖.

    如果我在我的 CRA 应用上运行 jest,我会收到这个错误:

    If I run jest on my CRA app, I get this error:

    PS C:UserspupenoDocumentsFlexpoint Techjsexp7frontend> jest
     FAIL  src/App.test.tsx
      ● 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: C:UserspupenoDocumentsFlexpoint Techjsexp7frontendsrcApp.test.tsx: Unexpected token (6:29)
    
          4 | 
          5 | test("renders Facebook link", () => {
        > 6 |   const {getByText} = render(<App/>)
            |                              ^
          7 |   const linkElement = getByText(/Loading.../i)
          8 |   expect(linkElement).toBeInTheDocument()
          9 | })
    
          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:212:21)
    
    Test Suites: 1 failed, 1 total
    Tests:       0 total
    Snapshots:   0 total
    Time:        2.234s
    Ran all test suites.
    

    我正在尝试在不弹出的情况下执行此操作,以免失去 CRA 的好处.我明白,如果我退出,我几乎可以为所欲为.

    I'm trying to do this without ejecting, to not lose the benefits of CRA. I understand that if I eject I can do pretty much whatever I want.

    推荐答案

    create-react-app Jest 配置不应该在没有弹出的情况下可用.react-script test 使用动态生成的配置以编程方式运行 Jest.它在 eject 上导出到静态配置文件.

    create-react-app Jest configuration isn't supposed to be available without ejection. react-script test programmatically runs Jest with dynamically generated configuration. It's exported to static configuration file on eject.

    问题是弹出仍然不允许以与 Jest CLI 相同的方式运行测试,因为在弹出的项目中,Jest 仍然通过 scripts/test.js 以编程方式运行.该脚本负责设置 CRA 环境变量,它们应该另外提供给 Jest CLI.这个 应该在 jest.config.js 或 globalSetup 文件中进行评估:

    The problem is that ejection still doesn't allow to run tests the same way with Jest CLI because in ejected project, Jest still runs programmatically via scripts/test.js. The script is responsible for setting up CRA environment variables, they should be additionally supplied to Jest CLI. This should be evaluated in either jest.config.js or globalSetup file:

    process.env.BABEL_ENV = 'test';
    process.env.NODE_ENV = 'test';
    process.env.PUBLIC_URL = '';
    require('react-scripts/config/env');
    

    弹出

    考虑到未弹出的项目不会提供生成的项目(如脚手架)固有的任何好处,最好在需要任何自定义时立即弹出.

    Eject

    Considering that unejected projects doesn't provide any benefits that are inherent to generated projects like scaffolding, it's preferable to eject as soon as any customization is needed.

    如果需要保持项目不被弹出,可以克隆和弹出,然后Jest配置(config/jest/*.* and jest entry from package.json) 转移到未弹出的项目.这可以通过 Git 分支来实现.

    If it's necessary to keep the project unejected, it can be cloned and ejected, then Jest configuration (config/jest/*.* and jest entry from package.json) is transferred to unejected project. This can be achieved with Git branches.

    或者,它可以通过依赖于 react-scripts 内部结构:

    Alternatively, its possible to retrieve generated configuration similarly to how CRA does this via a hack that relies on react-scripts internals:

    jest.config.js

    process.env.BABEL_ENV = 'test';
    process.env.NODE_ENV = 'test';
    process.env.PUBLIC_URL = '';
    require('react-scripts/config/env');
    
    const path = require('path');
    const createJestConfig = require('react-scripts/scripts/utils/createJestConfig');
    
    module.exports = createJestConfig(
      relativePath => require.resolve(path.join('react-scripts', relativePath)),
      __dirname, // given that Jest config is in project root
      false
    );
    

    这篇关于如何让 jest 使用与 create-react-app 上的 react-script 测试相同的配置运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆