如何测试componentDidMount有条件地进行API调用

时间:2018-05-15 07:48:18

标签: javascript reactjs enzyme jest

我在我的应用程序中使用了React。我在我的componentDidMount中进行API调用,但它是有条件的。我在组件中的代码是

componentDidMount() {
    if (!this.props.fetch) {
      fetchAPICall()
        .then(() => {
          /** Do something **/
        });
    }
  }

我写的测试为:

it('should not fetch ', () => {
      const TFCRender = mount(<Component fetch />);
      const didMountSpy = jest.spyOn(TFCRender.prototype, 'componentDidMount');
      expect(didMountSpy).toHaveBeenCalledTimes(1);
      expect(fetchAPICall).toHaveBeenCalledTimes(0);
    });

测试让我误以为

TypeError: Cannot read property 'componentDidMount' of undefined

我做错了什么,测试这种情况的正确方法是什么。

1 个答案:

答案 0 :(得分:2)

official docs开始,您需要在安装之前spy组件。

以下是我使用create-react-app创建的一个工作示例。我还在示例代码中添加了一些注释:

<强> App.js

import { fetchAPICall } from './api';

class App extends Component {
  componentDidMount() {
    if (!this.props.fetch) {
      fetchAPICall().then(console.log);
    }
  }
  render() {
    return <div>Testing the result</div>;
  }
}

export default App;

<强> api.js

export const fetchAPICall = () => {
  return Promise.resolve('Getting some data from the API endpoint');
};

<强> App.test.js

import Component from './App';
import * as apis from './api'; // assuming you have a separate file for these APIs

// Mock the fetchAPICall, and since the data fetching is asynchronous 
// you have to mock its implementation with Promise.resolve()`
apis.fetchAPICall = jest.fn(() => Promise.resolve('test'));

describe('spyOn', () => {
  let didMountSpy; // Reusing the spy, and clear it with mockClear()
  afterEach(() => {
    didMountSpy.mockClear();
  });

  didMountSpy = jest.spyOn(Component.prototype, 'componentDidMount');

  test('should not fetch ', () => {
    // Ensure the componentDidMount haven't called yet.
    expect(didMountSpy).toHaveBeenCalledTimes(0);

    const TFCRender = mount(<Component fetch />);
    expect(didMountSpy).toHaveBeenCalledTimes(1);
    expect(apis.fetchAPICall).toHaveBeenCalledTimes(0);
  });

  test('should fetch', () => {
    expect(didMountSpy).toHaveBeenCalledTimes(0);

    const TFCRender = mount(<Component fetch={false} />);
    expect(didMountSpy).toHaveBeenCalledTimes(1);
    expect(apis.fetchAPICall).toHaveBeenCalledTimes(1);
  });
});

不确定这是否是最佳做法,但这就是我通常编写自己的测试的方法。

希望这有帮助!