【问题标题】:Testing a fetch.catch in custom hook在自定义钩子中测试 fetch.catch
【发布时间】:2020-07-10 00:59:10
【问题描述】:

我有这个自定义钩子:

import React from 'react';
import { useMessageError } from 'components/Message/UseMessage';

export interface Country {
  code: string;
  name: string;
}

export default function useCountry(): Array<Country> {
  const [countries, setCountries] = React.useState<Country[]>([]);
  const { showErrorMessage } = useMessageError();

  React.useEffect(() => {
    fetch('/api/countries', {
      method: 'GET',
    })
      .then(data => data.json())
      .then(function(data) {
        // ..
      })
      .catch(() => showErrorMessage());
  }, []);

  return countries;
}

如果会有无效响应,我想测试捕获错误。这样,由于showErrorMessage(),应该会出现错误消息。我有这个测试:

const showErrorMessage = jest.fn();

jest.mock('components/Message/UseMessage', () => ({
  useMessageError: () => ({
    showErrorMessage: showErrorMessage,
  }),
}));

import useCountry from 'components/Country/useCountry';
import { renderHook } from '@testing-library/react-hooks';
import { enableFetchMocks } from 'jest-fetch-mock';
enableFetchMocks();

describe('The useCountry hook', () => {
  it('should show error message', async () => {
    jest.spyOn(global, 'fetch').mockImplementation(() =>
      Promise.resolve({
        json: () => Promise.reject(),
      } as Response),
    );

    const { result, waitForNextUpdate } = renderHook(() => useCountry());
    await waitForNextUpdate();

    expect(fetch).toHaveBeenCalled();
    expect(showErrorMessage).toHaveBeenCalled();
    expect(result.current).toEqual([]);
  });
});

但是,我得到一个错误:

超时 - 在 jest.setTimeout.Timeout 指定的 5000 毫秒超时内未调用异步回调。在 jest.setTimeout.Error 指定的 5000 毫秒超时内未调用异步回调

我在这里做错了什么?我认为它与await waitForNextUpdate(); 有某种关系,但我真的不确定以及如何管理它。

【问题讨论】:

  • 这肯定与卡在await waitForNextUpdate(); 的进程有某种关系你试过调试它吗?如果您在 Webstorm 上,只需右键单击测试并使用“调试”并逐步前进。

标签: javascript typescript jestjs jest-fetch-mock react-hooks-testing-library


【解决方案1】:

waitForNextUpdate() 等待下一次更新,但你的钩子不会触发它,因为它只调用showErrorMessage()。看看this sandbox

作为一个简单的解决方案,可以添加一些触发更新的内容:

  React.useEffect(() => {
    fetch('/api/countries', {
      method: 'GET',
    })
      .then(data => data.json())
      .then(function(data) {
        // ..
      })
      .catch(() => { 
        showErrorMessage();
        // trigger update in any suitable way, for example:
        setCountries([]); 
      });
  }, []);

但是以某种方式重构它可能会更好。例如,您可以对错误使用单独的钩子和状态:

export default function useCountry(): Array<Country> {
  const [countries, setCountries] = React.useState<Country[]>([]);
  const [error, setError] = React.useState(null);
  const { showErrorMessage } = useMessageError();

  React.useEffect(() => {
    fetch('/api/countries', {
      method: 'GET',
    })
      .then(data => data.json())
      .then(function(data) {
        // ..
      })
      .catch(() => setError(true));
  }, []);
  
  React.useEffect(() => {
    if (error) {
      showErrorMessage()
    }
  }, [error]);

  return countries;
}

【讨论】:

  • 确实有效。谢谢!但我有一个问题。只是为了使测试工作而添加一些更新组件是一种好习惯吗,就像在这种情况下?
  • @KrzysztofTrzos 不,仅出于测试目的这样做不是一个好习惯,但通常处理异步操作,您必须处理诸如防止多个请求、竞争条件和取消之类的事情,因此您需要无论如何,一些额外的状态和更新。
猜你喜欢
  • 1970-01-01
  • 2022-01-13
  • 2020-02-19
  • 2020-05-25
  • 1970-01-01
  • 2021-04-25
  • 1970-01-01
  • 2021-12-26
  • 2020-01-26
相关资源
最近更新 更多