代码之家  ›  专栏  ›  技术社区  ›  Krimson

模拟导入以测试函数逻辑

  •  0
  • Krimson  · 技术社区  · 6 年前

    假设我有以下文件。

    此文件导入 promiseFunction 在图书馆,我想测试一下 doSomething() 功能。

    特别是,在承诺解决或失败时断言国家

    // file: MyComponent.js
    
    import promiseFunction from 'somewhere';
    
    class MyClass extends Component {
    
      doSomething = () => {
    
        promiseFunction()
          .then((data) => {
    
            this.setState({...this.state, name: data.name});
    
          }.catch(() => {
    
            this.setState({...this.state, error: 'error'});
    
          });
    
      }
    }
    

    我怎么嘲笑 允诺函数 那是进口的。或者只是导入的任何函数。

    // file: MyClass.spec.js
    it('sets error in state when doSomething() is rejected', () => {
      const wrapper = shallow(<MyClass />);
    
      // How do I mock promiseFunction here?
      wrapper.instance().doSomething();
    
      expect(wrapper.state().error).toEqual('error');
    });
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Brian Adams    6 年前

    你可以使用 spyOn mockImplementation

    下面是一个工作示例:

    // ---- somewhere.js ----
    const promiseFunction = () => {
      return Promise.resolve({name: 'name from promiseFunction'});
    }
    export default promiseFunction;
    
    
    
    // ---- myclass.js ----
    import * as React from 'react';
    import promiseFunction from './somewhere';
    
    export class MyClass extends React.Component {
      doSomething = () => {
        // return the Promise so the test can wait for it
        return promiseFunction()
          .then((data) => {
            this.setState({...this.state, name: data.name});
          }).catch(() => {
            this.setState({...this.state, error: 'error'});
          });
      }
      render() {
        return <div>This is MyClass</div>;
      }
    }
    
    
    
    // ---- myclass.test.js ----
    import { shallow } from 'enzyme';
    import * as React from 'react';
    import { MyClass } from './myclass';
    import * as somewhere from './somewhere';
    
    describe('MyClass', () => {
      it('sets error in state when promiseFunction rejects', async () => {
        // set up mock for promiseFunction
        const mock = jest.spyOn(somewhere, 'default');
        mock.mockImplementation(() => Promise.reject());
    
        const wrapper = shallow(<MyClass />);
    
        await wrapper.instance().doSomething();
    
        expect(wrapper.state().error).toEqual('error');
    
        // restore promiseFunction
        mock.mockRestore();
      });
    });