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

Lew*_*wis 7 sinon reactjs jestjs enzyme

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

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

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

使用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);
  });
});
Run Code Online (Sandbox Code Playgroud)

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

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

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

And*_*rle 6

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

但如果你真的想测试它:

const spy = jest.fn()
const componentDidMount = Foo.prototype.componentDidMount
Foo.prototype.componentDidMount = function(){
  spy()
  componentDidMount()
}
Run Code Online (Sandbox Code Playgroud)


Rya*_* H. 6

从 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();
  });
});
Run Code Online (Sandbox Code Playgroud)

jest.spyOn返回一个模拟函数,其中包含所有通常可用的方法,例如mockClearmockResetmockRestore

mount确保在使用酶或create反应测试渲染器之前设置您的间谍,以便创建的实例具有对正在监视的模拟函数的引用。