加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 20:11:12 所属栏目:百科 来源:网络整理
导读:完整DOM渲染的酶文档 here包含以下使用Sinon监视生命周期方法的示例: describe('Foo /',() = { it('calls componentDidMount',() = { sinon.spy(Foo.prototype,'componentDidMount'); const wrapper = mount(Foo /); expect(Foo.prototype.componentDidMoun
完整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 />',() => {
    jest.fn(App.prototype,'componentDidMount');
    const wrapper = mount(<App />);
    expect(App.prototype.componentDidMount.mock.calls.length).toBe(1);
  });
});

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

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

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

解决方法

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读