设置 Jest 和 Enzyme 来测试 React 15 找不到模块 react/lib/ReactTestUtils

Posted

技术标签:

【中文标题】设置 Jest 和 Enzyme 来测试 React 15 找不到模块 react/lib/ReactTestUtils【英文标题】:Setting up Jest and Enzyme to test React 15 cannot find module react/lib/ReactTestUtils 【发布时间】:2017-03-20 20:28:11 【问题描述】:

我有一个 react 项目,正在尝试设置一些测试

由于以下设置指南/问题:

https://github.com/facebook/jest/issues/1353, https://github.com/facebook/react/issues/7386, http://facebook.github.io/jest/docs/tutorial-react.html#content, http://airbnb.io/enzyme/

我已经安装了以下依赖项:

react-addons-test-utils 15.3.2 反应 15.4.0-rc.4 react-dom 15.4.0-rc-4 开玩笑 16.0.2 babel-jest 16.0.0 babel-preset-es2015 6.18.0 babel-preset-es2015-loose 7.0.0 babel-preset-react 6.16.0

我的 package.json 包含以下 Jest 配置:

 "jest": 
    "bail": false,
    "collectCoverage": true,
    "collectCoverageFrom": [
      "<rootDir>/src/**/*.js",
      "!<rootDir>/node_modules/**"
    ],
    "coverageDirectory": "coverage",
    "coveragePathIgnorePatterns": [
      "<rootDir>/node_modules"
    ],
    "coverageThreshold": 
      "global": 
        "branches": 50,
        "functions": 50,
        "lines": 50,
        "statements": 50
      
    ,
    "globals": 
      "SOURCEMAP": true
    ,
    "modulePaths": [
      "<rootDir>/src",
      "<rootDir>/sass",
      "<rootDir>/public",
      "<rootDir>/node_modules"
    ],
    "resetModules": true,
    "testPathDirs": [
      "<rootDir>/test"
    ],
    "testRegex": "(/test/.*|\\.(test|spec))\\.(js|jsx)$",
    "verbose": true
  

我的组件 (GenericButton) 放在 &lt;rootDir&gt;/components/buttons/GenericButton.js 中,我的测试放在 &lt;rootDir&gt;/test/componnets/buttons/GenericButtonTest.js 中,内容如下:

import React from 'react';
import GenericButton from 'components/buttons/GenericButton';
import  shallow  from 'enzyme';
import  shallowToJson  from 'enzyme-to-json';
import ReactTestUtils from 'react-addons-test-utils'

describe('Generic Button', () => 
    test('Button action called when clicked', () => 
        var clicked = false;
        const component = shallow(
            <GenericButton action=() => 
                clicked = true;
            />
        );

        console.log("Clicking the button!");
        ReactTestUtils.Simulate.click(component);
        expect(clicked).toBeTruthy();
    );
)

我的 babelrc 文件如下:


  "presets": [
    "es2015-loose",
    "react",
    "stage-0"
  ],
  "plugins": [
    "babel-root-slash-import",
    "transform-decorators-legacy",
    "react-hot-loader/babel",
    "transform-runtime"
  ],
  "compact": true,
  "ignore": [
    "/node_modules/(?!react-number-input)"
  ]

但是,当我运行测试时,我收到以下错误:

> admin-console@4.1.0 test C:\path\to\project
> jest

 FAIL  test\components\buttons\GenericButtonTest.js
  ● Test suite failed to run

    Cannot find module 'react/lib/ReactTestUtils' from 'index.js'

      at Resolver.resolveModule (node_modules\jest-resolve\build\index.js:144:17)
      at Object.<anonymous> (node_modules\react-addons-test-utils\index.js:1:107)
      at node_modules\enzyme\build\react-compat.js:128:19

----------|----------|----------|----------|----------|----------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
----------|----------|----------|----------|----------|----------------|
All files |  Unknown |  Unknown |  Unknown |  Unknown |                |
----------|----------|----------|----------|----------|----------------|
Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        5.843s
Ran all test suites.
  console.error node_modules\enzyme\build\react-compat.js:131
    react-addons-test-utils is an implicit dependency in order to support react@0.13-14. Please add the appropriate version to your devDependencies. See https://github.com/airbnb/enzyme#installation

npm ERR! Test failed.  See above for more details.

我该怎么做才能让这个简单的测试通过?


编辑:react-addons-test-utils 需要的文件 react/lib/ReactTestUtils 不在 node_modules/react/lib 文件夹中。

通过将 react-addons-test-utils 升级到 15.4.0-rc.3 解决了这个问题,但后来我得到了:

TypeError: Cannot read property '__reactInternalInstance$t476n6b4jes0zxw0n18vbzkt9' of undefined

  at getClosestInstanceFromNode (node_modules\react-dom\lib\ReactDOMComponentTree.js:106:11)
  at Object.getInstanceFromNode (node_modules\react-dom\lib\ReactDOMComponentTree.js:140:14)
  at Object.click (node_modules\react-dom\lib\ReactTestUtils.js:326:74)
  at Object.<anonymous> (test\components\buttons\GenericButtonTest.js:17:67)

【问题讨论】:

【参考方案1】:

目前,您不能在测试中同时使用 ReactTestUtilsenzyme。幸运的是,您也可以使用酶模拟点击。唯一的问题是simulate不会传播到子组件,所以你需要先找到子组件并在其上调用simulate

import React from 'react';
import GenericButton from 'components/buttons/GenericButton';
import  shallow  from 'enzyme';
import  shallowToJson  from 'enzyme-to-json';

describe('Generic Button', () => 
    test('Button action called when clicked', () => 
        var clicked = false;
        const component = shallow(
            <GenericButton action=() => 
                clicked = true;
            />
        );
        component.find('selectrorOfChildWithClickHandler').first().simulate('click')
        expect(clicked).toBeTruthy();
    );
)

【讨论】:

ReferenceError: click is not defined -------- at Object. (test\components\buttons\GenericButtonTest.js:18:42) ------- - 在 process._tickCallback (internal\process\next_tick.js:103:7) 我的回答有错别字。 该错误已解决。现在:方法“props”仅用于在单个节点上运行。找到了 0 个。 ----- 在 ShallowWrapper.single (node_modules\enzyme\build\ShallowWrapper.js:1401:17) -----在 ShallowWrapper.props (node_modules\enzyme\build\ShallowWrapper.js:791:21) -- ---在 ShallowWrapper.prop (node_modules\enzyme\build\ShallowWrapper.js:997:21) -----在 ShallowWrapper.simulate (node_modules\enzyme\build\ShallowWrapper.js:762:28) ---- -at Object. (test\components\buttons\GenericButtonTest.js:17:33) -----at process._tickCallback (internal\process\next_tick.js:103:7) 抱歉,再次更新,需要first()从结果列表中获取第一个节点 谢谢。似乎剩下的只是我的实际组件的一个问题,因为变量没有得到更新。 (除非你看到一些明显的东西,我现在会自己研究一下)【参考方案2】:

酶需要这些依赖:

npm i --save-dev enzyme
npm i --save-dev react-addons-test-utils
npm i --save-dev react-dom

安装为devDependencies。这对我有用。

【讨论】:

以上是关于设置 Jest 和 Enzyme 来测试 React 15 找不到模块 react/lib/ReactTestUtils的主要内容,如果未能解决你的问题,请参考以下文章

React Redux:使用 Enzyme/Jest 测试 mapStateToProps 和 mapDispatchToProps

Jest 和 Enzyme 的问题

如何使用 Jest - Enzyme 测试 React 中 mapStateToProps 中的方法

Jest+Enzyme测试React组件(上)

如何在 React with Jest 和 Enzyme 中测试表单提交?无法读取未定义的属性“preventDefault”

Jest / Enzyme - 生命周期方法中的模拟异步函数