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

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

问题描述

用于完整 DOM 渲染的 Enzyme 文档此处 包含以下间谍示例关于使用 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 那样引用相同的函数 spy.

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,因为 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天全站免登陆