如何使用Jest和Enzyme模拟React组件生命周期方法? [英] How to mock a React component lifecycle method with Jest and Enzyme?

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

问题描述

用于完整DOM渲染的酶文档此处包含以下间谍示例使用Sinon的生命周期方法:

The Enzyme docs for Full DOM Rendering here contains the following example of spying on a lifecycle method with Sinon:

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

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

使用Jest的模拟功能相当于什么?

What is the equivalent to this using mock functions from Jest?

我正在使用Create-React-App,如果可以通过Jest实现相同的功能,我宁愿不包括Sinon.

I'm using Create-React-App, and would rather not include Sinon if the same can be achieved with Jest.

这是我希望测试看起来像的样子:

Here's what I'd expect the test to look like:

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相同的函数间谍.

In this case, App.prototype.componentDidMount doesn't reference the same function spy as it would do with Sinon.

关于模拟函数实际工作方式的Jest文档受到限制.我已经按照此处的讨论,进行了有关jest.fn()的操作,但是似乎并不等同于sinon.spy().

The Jest docs on how mock functions actually work are a bit limited. I've followed the discussion here around what jest.fn() is doing, but it seems it's not really equivalent to sinon.spy().

如何用Jest复制该测试?

How can I replicate that test with Jest?

推荐答案

这种方式不能有效地解决问题,因为jest.fn仅具有用于实现的参数.但更重要的是,您不应监视要测试的对象的内部.您应该将Foo视为一个黑匣子,您可以在其中放置一些属性并重新渲染一些内容.然后,您意识到无需测试Foo的内部功能(如componentDidMount)是否被调用.唯一重要的是黑匣子的输出.

This will not work with jest this way as jest.fn only have a parameter for the implementation. But more important, you should not spy on the internals of the object you want to test. You should think of Foo as a black box where you can put some properties in and get some stuff rendered back. Then you realize that there is no need to test that internal functions of Foo, like componentDidMount, get called. The only thing that matters is the output of the black box.

但是,如果您真的想要进行测试,则:

But if you really want do test it anyway:

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

这篇关于如何使用Jest和Enzyme模拟React组件生命周期方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆