我正在从 Mocha 切换到 Jest,我想知道是否有办法监视 React 方法。例如,假设我的组件中有以下方法(忽略 sdk
库,它只是构造一个 jQuery Ajax 调用):
getData() {
sdk.getJSON('/someURL').done(data => {
this.setState({data});
});
}
使用 Sinon,我会像这样监视原型(prototype)来测试它:
it('should call getData', () => {
sinon.spy(Component.prototype, 'getData');
mount(<Component />);
expect(Component.prototype.getData.calledOnce).to.be.true;
});
这将在不模拟方法的情况下确保代码覆盖率。 Jest 中有类似的功能吗?
编辑:此外,如果此功能不存在,测试 API 调用的下一个最佳策略是什么?
最佳答案
实际上你可以使用 jest.spyOn jest.spyOn
如果在创建组件时调用方法,请使用:
import { mount } from 'enzyme';
describe('My component', () => {
it('should call getData', () => {
const spy = jest.spyOn(Component.prototype, 'getData');
mount(<Component />);
expect(spy).toHaveBeenCalledTimes(1)
});
})
或者如果你在你的 DOM 中有它并且方法使用 bind 你可以使用:
import { shallow } from 'enzyme';
describe('My component', () => {
it('should call getData', () => {
const wrapper = shallow(<Component />);
const instance = wrapper.instance()
const spy = jest.spyOn(instance, 'getData');
wrapper.find('button').simulate('click')
expect(spy).toHaveBeenCalledTimes(1)
});
})
关于javascript - 开 Jest 监视功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42430368/