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

问题描述 投票:0回答:1

我正在尝试测试使用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测试该钩子的所有可能状态(加载,错误和值)?

谢谢!!!

reactjs typescript jestjs react-hooks enzyme
1个回答
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请求中的参数。因此,您可能想添加更多测试用例来检查该部分。

© www.soinside.com 2019 - 2024. All rights reserved.