【问题标题】:How to test a React Component with Jest and Enzyme如何使用 Jest 和 Enzyme 测试 React 组件
【发布时间】:2017-04-13 01:00:26
【问题描述】:

使用 enzyme-example-jest Github project 我可以克隆 repo 并运行测试:

git clone https://github.com/lelandrichardson/enzyme-example-jest.git
cd enzyme-example-jest
yarn install
yarn test

但是,我取消了Foo-test.js 的第 11 行的注释:

expect(shallow(<Foo />).contains(<div className="foo" />)).toBe(true);

所以文件现在看起来像这样:

import React from 'react';
import { shallow, mount, render } from 'enzyme';

jest.dontMock('../Foo');

const Foo = require('../Foo');

describe("A suite", function() {
  it("contains spec with an expectation", function() {
    expect(true).toBe(true);
    expect(shallow(<Foo />).contains(<div className="foo" />)).toBe(true);
  });

  it("contains spec with an expectation", function() {
    //expect(shallow(<Foo />).is('.foo')).toBe(true);
  });

  it("contains spec with an expectation", function() {
    //expect(mount(<Foo />).find('.foo').length).toBe(1);
  });
});

当我运行测试时,我现在得到了这个错误:

yarn test v0.17.8
$ jest
Using Jest CLI v0.8.2, jasmine1
Running 1 test suite...Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).
 FAIL  src/__tests__/Foo-test.js (0.931s)
● A suite › it contains spec with an expectation
  - TypeError: Component is not a function
        at StatelessComponent.render (node_modules/react/lib/ReactCompositeComponent.js:44:10)
1 test failed, 2 tests passed (3 total in 1 test suite, run time 1.281s)
error Command failed with exit code 1.

如何成功运行此测试?

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案1】:

    'Foo' 是用 ES6 类语法定义的,但在 Foo-test.js 中是 require 所必需的。使用import 将修复它。

    替换这个

    const Foo = require('../Foo');

    有了这个

    从 '../Foo' 导入 Foo;

    【讨论】:

      猜你喜欢
      • 2017-02-12
      • 2018-08-20
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 2017-11-10
      • 2020-08-07
      • 2017-11-30
      相关资源
      最近更新 更多