测试道具是否通过(不使用酶)

时间:2019-01-28 09:47:46

标签: reactjs

我想测试我的道具是否通过,但是不使用酶,

我试图在Internet上找到文档,但是所有教程都与酶有关。

describe('App Component', () => {
  it('renders the Counter wrapper', () => {
    const wrapper = shallow(<App />);
    expect(wrapper.find(Counter)).to.have.length(1);
  });

  it('passes all props to Counter wrapper', () => {
    const wrapper = shallow(<App />);
    let counterWrapper = wrapper.find(Counter);

    expect(counterWrapper.props().counter).to.equal(0);

    wrapper.setState({ counter: -1 });

    counterWrapper = wrapper.find(Counter);
    expect(counterWrapper.props().counter).to.equal(-1);
  });

有人可以帮我吗?我可以开玩笑吗?还是我需要像“ react-testing-library”这样的第三方库?

1 个答案:

答案 0 :(得分:2)

shallow主要用于隔离的单元测试,就像上面列出的那样,只声明被测试单元的实现。它提供了一些React本身不存在的工具(以及不兼容的行为)。

react-testing-library主要用于黑盒功能测试,可以断言单元对最终DOM的影响。

React自己的ReactTestUtils还提供一些基本功能,酶的子集和react-testing-library功能,包括用于独立测试的shallow renderer

可以进行隔离的测试并在没有酶的情况下断言实现,这会产生样板代码。该方法并非特定于测试库,可以使用任何渲染器(包括React的测试渲染器的snapshot testing)来实现。除测试单元(Counter组件)外的所有内容(App组件)都应使用Jest模拟,例如:

  it('passes all props to Counter wrapper', async () => {
    const CounterMock = jest.fn(() => 'Counter');
    jest.mock('./counter-module', () => CounterMock);
    const App = await import('./app-module');

    // render <App/> and assert that the result is <div>Counter</div> 

    expect(CounterMock).toBeCalledWith({ counter: 0 });
  });