How to test a React Component with Jest and Enzyme

此生再无相见时 提交于 2019-12-12 02:21:43

问题


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

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.

How do I successfully run this test?


回答1:


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

Replace this

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

with this

import Foo from '../Foo';



来源:https://stackoverflow.com/questions/40858984/how-to-test-a-react-component-with-jest-and-enzyme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!