模拟导入以测试功能逻辑

时间:2018-07-29 00:42:59

标签: javascript testing jestjs sinon enzyme

让我说我有以下文件。

此文件从库中导入了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'});

      });

  }
}

如何模拟正在导入的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');
});

1 个答案:

答案 0 :(得分:0)

您可以将spyOnmockImplementation组合使用

这是一个有效的示例:

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