如何使用Jest和Enzyme测试React组件

如何使用Jest和Enzyme测试React组件

本文介绍了如何使用Jest和Enzyme测试React组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 enzyme-example-jest Github项目,我可以克隆回购并运行测试:

Using the enzyme-example-jest Github project I am able to clone the repo and run the tests:

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

但是,我没有注释Foo-test.js的第11行:

However, I uncommented line 11 of Foo-test.js:

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

文件现在看起来像这样:

So that the file now looks like this:

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);
  });
});

当我运行测试时,我现在得到此错误:

And when I run the test I now get this error:

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.

如何成功运行此测试?

推荐答案

'Foo'是使用ES6类语法定义的,但Foo-test.js中的require则是必需的.使用import可以解决此问题.

'Foo' is defined with ES6 class syntax but is required with require in Foo-test.js. Using import will fix it.

替换此

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

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

与此

从"../Foo"导入Foo;

import Foo from '../Foo';

这篇关于如何使用Jest和Enzyme测试React组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 04:28