使用Jest / Enzyme测试延迟的自定义React钩子?

时间:2020-03-03 20:21:48

标签: reactjs typescript jestjs react-hooks enzyme

我正在尝试测试使用useStateuseEffect以及模拟延迟加载某些数据的setTimeout的自定义钩子。简化

const useCustomHook = (id: number) => {
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(false);
  const [value, setValue] = React.useState<string>();

  React.useEffect(() => {
    const dummy = ["foo", "bar", "baz"];
    // simulate remote call with delay
    setTimeout(() => {
      id < 3 ? setValue(dummy[id]) : setError(true);
      setLoading(false);
    }, 1500);
  }, [id]);

  return [loading, error, value];
};

const App = () => {
  const [loading, error, value] = useCustomHook(1);

  if (loading) { return <div>Loading...</div>; }
  if (error) { return <div>Error</div>; }
  return <h1>{value}</h1>;
};

https://codesandbox.io/s/react-typescript-z1z2b

您如何使用Jest和Enzyme测试该挂钩的所有可能状态(加载,错误和值)?

提前谢谢!!!

1 个答案:

答案 0 :(得分:0)

我想您真正想要的是在useEffect挂钩内发送API请求。 (对不起,如果我误解了您的意图)

如果是,我会检查

  • API请求已发送
  • 首先显示加载内容
  • API请求失败时显示错误
  • API请求成功时显示结果

测试应如下所示。

describe('App', () => {
  beforeEach(() => {
    fetch.resetMocks();
  });

  it('should fetch the request', async () => {
    await act(async () => {
      await mount(<App />)
    })

    expect(fetch).toBeCalledWith('https://dog.ceo/api/breeds/image/random');
  });

  it('should show loading at first', () => {
    // mock useEffect to test the status before the API request
    jest
      .spyOn(React, 'useEffect')
      .mockImplementationOnce(() => {}); 

    const comp = mount(<App />)

    expect(comp.text()).toBe('Loading...');
  });

  it('should display error if api request fail', async () => {
    fetch.mockRejectOnce();
    let comp;

    await act(async () => {
      comp = await mount(<App />);
    })
    comp.update();

    expect(comp.text()).toBe('Error');
  });

  it('should display result if api request success', async () => {
    fetch.mockResponseOnce(JSON.stringify({
      message: "https://images.dog.ceo/breeds/mastiff-tibetan/n02108551_1287.jpg",
      status: "success"
    }));
    let comp;

    await act(async () => {
      comp = await mount(<App />);
    })
    comp.update();


    expect(comp.find('img')).toHaveLength(1);
    expect(comp.find('img').prop('src'))
      .toBe('https://images.dog.ceo/breeds/mastiff-tibetan/n02108551_1287.jpg');
  });
});

以下是供参考的存储库:https://github.com/oahehc/stackoverflow-answers/tree/60514934/src

此外,您将id传递到useCustomHook中,我想这将用作API请求中的参数。因此,您可能想添加更多测试用例来检查该部分。

相关问题