【问题标题】:Jest spy on functionality开玩笑监视功能
【发布时间】:2017-07-14 19:08:05
【问题描述】:

我正在从 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 调用的下一个最佳策略是什么?

【问题讨论】:

    标签: javascript reactjs jestjs


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      spyOn 方法是几天前在 v19 中引入的,它完全符合您的要求

      【讨论】:

      • 如果您在此处提供示例用法以及您自己的解释,而不是仅在答案中发布链接,那将是一个更好的答案。
      • 这个答案甚至是有害的,因为它建议使用 jasmine-jest2 包附带的全局 spyOn 来缓解从 jasmine 迁移。但是,该行为似乎与 jest.spyOn() 不同,因为全局 spyOn(如 jasmine 的)默认情况下不会调用!
      【解决方案3】:

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

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

      【讨论】:

      • Sinon.spyjest.spyOn 一样吗?
      【解决方案4】:

      我在 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"

      【讨论】:

        猜你喜欢
        • 2019-05-08
        • 1970-01-01
        • 2020-01-02
        • 1970-01-01
        • 2018-09-25
        • 1970-01-01
        • 2022-11-18
        • 2020-10-08
        • 1970-01-01
        相关资源
        最近更新 更多