完整 DOM 渲染的 Enzyme 文档 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 相同的函数 spy 。
有关模拟函数实际工作方式的 Jest 文档有点有限。我关注了讨论here围绕 jest.fn() 正在做的事情,但似乎它并不真正等同于 sinon.spy()。
如何使用 Jest 复制该测试?
最佳答案
这不适用于 jest,因为 jest.fn
只有一个用于实现的参数。但更重要的是,您不应该监视要测试的对象的内部结构。您应该将 Foo
视为一个黑盒子,您可以在其中放入一些属性并获取一些渲染回来的内容。然后您意识到不需要测试 Foo
的内部函数(例如 componentDidMount
)被调用。唯一重要的是黑匣子的输出。
但是如果你真的想测试一下:
const spy = jest.fn()
const componentDidMount = Foo.prototype.componentDidMount
Foo.prototype.componentDidMount = function(){
spy()
componentDidMount()
}
关于reactjs - 如何使用 Jest 和 Enzyme 模拟 React 组件生命周期方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41461011/