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

标签 javascript reactjs enzyme jestjs

我在我的应用程序中使用 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

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

最佳答案

来自official docs ,您需要在安装组件之前监视该组件。

以下是我使用 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);
  });
});

不确定这是否是最佳实践,但这是我通常编写自己的测试的方式。

希望对您有所帮助!

关于javascript - 如何有条件地测试 componentDidMount 进行 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50344948/

相关文章:

javascript - 追加 <select> 元素列表

javascript - WebRTC - 在 web 应用程序中选择主摄像头(当设备有多个后置摄像头时)

javascript - Jest 快照 @import CSS 失败

javascript - 开 Jest - TypeError : Cannot read property 'fn' of undefined

javascript - 错误 : Expected mock function to have been called

reactjs - 扩展 enzyme js

javascript - 构建 Angular 6 应用程序后运行命令行

javascript - 将多个项目拖动到 d3 中的另一个项目内

javascript - 如何从嵌套对象的数组中删除元素? (lodash)

javascript - React.StrictMode : SetState function in useEffect is run multiple times when effect is run once