开玩笑监视功能

Jest spy on functionality

我正在从 Mocha 切换到 Jest,我想知道是否有办法监视 React 方法。例如,假设我的组件中有以下方法(忽略 sdk 库,它只是构造一个 jQuery Ajax 调用):

getData() {
    sdk.getJSON('/someURL').done(data => {
        this.setState({data});
    });
}

使用 Sinon,我会像这样监视原型来测试它:

it('should call getData', () => {
    sinon.spy(Component.prototype, 'getData');
    mount(<Component />);
    expect(Component.prototype.getData.calledOnce).to.be.true;
});

这将在不模拟方法的情况下确保代码覆盖率。 Jest 中有类似的功能吗?

编辑:此外,如果此功能不存在,测试 API 调用的下一个最佳策略是什么?

几天前在 v19 中引入了 spyOn 方法,它可以满足您的需求

您可以使用新的 spyOn 方法,或者下面的方法应该也能正常工作。

it('should call getData', () => {
    Component.prototype.getData = jest.fn(Component.prototype.getData);
    expect(Component.prototype.getData).toBeCalled();
});

实际上你可以使用 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)
  });
})

我在 React 16.8 中使用 Jest - 这对我有用:

  it("lifecycle method should have been called", () => {
    jest.spyOn(RedirectingOverlay.prototype, 'componentWillUnmount');
    jest.spyOn(RedirectingOverlay.prototype, 'componentDidMount');
    const wrapper = mount(<RedirectingOverlay message="Hi There!"/>);
    expect(RedirectingOverlay.prototype.componentDidMount).toHaveBeenCalledTimes(1)
    wrapper.unmount()
    expect(RedirectingOverlay.prototype.componentWillUnmount).toHaveBeenCalledTimes(1)
  })

同时使用:

  • "enzyme": "^3.6.0"
  • "jest": "23.5.0"
  • "enzyme-adapter-react-16": "^1.5.0"