簡體   English   中英

如何使用Jest和Enzyme測試React組件

[英]How to test a React Component with Jest and Enzyme

使用酶示例jest Github項目,我可以克隆存儲庫並運行測試:

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.

如何成功運行此測試?

“ Foo”是用ES6類語法定義的,但在Foo-test.js require是必需的。 使用import將修復它。

取代這個

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

有了這個

從'../Foo'導入Foo;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM