模拟导入以测试功能逻辑

Mock imports to test function logic

假设我有以下文件。

此文件从库中导入 promiseFunction,我想测试 doSomething() 函数。

特别是当 promise 解决或失败时断言状态

// 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'});

      });

  }
}

如何模拟正在导入的 promiseFunction。或者实际上只是正在导入的任何函数。

// 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');
});

您可以使用spyOn in combination with 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();
  });
});