在自定义挂钩中测试 fetch.catch

Testing a fetch.catch in custom hook

我有这个自定义挂钩:

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

但是,我收到一个错误:

Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error

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

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;
}