完整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 />', () => {
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相同的函数间谍。
关于模拟函数实际工作方式的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()
}
从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();
});
});
jest.spyOn用mock function,mockClear
和mockReset
等所有常用方法返回mockRestore
。
确保在使用酶或mount
与react-test-renderer进行create
之前设置您的间谍,以便创建的实例具有对被监视的模拟函数的引用。