如何使用Jest和Enzyme模拟React组件生命周期方法?

问题描述 投票:5回答:2

完整DOM渲染的酶文档here包含以下使用Sinon监视生命周期方法的示例:

describe('<Foo />', () => {

  it('calls componentDidMount', () => {
    sinon.spy(Foo.prototype, 'componentDidMount');
    const wrapper = mount(<Foo />);
    expect(Foo.prototype.componentDidMount.calledOnce).to.equal(true);
  });
});

使用Jest的模拟函数相当于什么?

我正在使用Create-React-App,如果使用Jest可以实现同样的目的,我宁愿不包括Sinon。

这是我期望测试的样子:

describe('<App />', () => {

  it('calls componentDidMount', () => {
    jest.fn(App.prototype, 'componentDidMount');
    const wrapper = mount(<App />);
    expect(App.prototype.componentDidMount.mock.calls.length).toBe(1);
  });
});

在这种情况下,App.prototype.componentDidMount不会引用与Sinon相同的函数间谍。

关于模拟函数实际工作方式的Jest文档有点受限。我跟着讨论here围绕jest.fn()做了什么,但它似乎并不等同于sinon.spy()。

我怎样才能用Jest复制那个测试?

reactjs sinon jestjs enzyme
2个回答
3
投票

这不会以这种方式使用jest,因为jest.fn只有实现的参数。但更重要的是,你不应该窥探你要测试的对象的内部。您应该将Foo视为一个黑盒子,您可以在其中放入一些属性并获取一些东西。然后你意识到没有必要测试Foo的内部函数,如componentDidMount,被调用。唯一重要的是黑匣子的输出。

但是如果你真的想要测试它呢:

const spy = jest.fn()
const componentDidMount = Foo.prototype.componentDidMount
Foo.prototype.componentDidMount = function(){
  spy()
  componentDidMount()
}

1
投票

从Jest 19开始,你可以这样做:

describe('<App />', () => {
  it('calls componentDidMount', () => {
    const spy = jest.spyOn(App.prototype, 'componentDidMount');
    const wrapper = mount(<App />);
    expect(spy).toHaveBeenCalled();
    spy.mockReset();
    spy.mockRestore();
  });
});

jest.spyOnmock functionmockClearmockReset等所有常用方法返回mockRestore

确保在使用酶或mount与react-test-renderer进行create之前设置您的间谍,以便创建的实例具有对被监视的模拟函数的引用。

© www.soinside.com 2019 - 2024. All rights reserved.