iT邦幫忙

2021 iThome 鐵人賽

DAY 16
0
import { render, screen, waitFor } from '@testing-library/react';
import { rest } from 'msw';
import News from '../News';
import { server } from '../../../mocks/server';

describe('<Users />', () => {
  test('should component show error message', async () => {
    server.resetHandlers(
      rest.get('http://localhost:5000/news', (req, res, ctx) => {
        return res(ctx.status(400));
      })
    );

    render(<News />);

    await waitFor(async () => {
      const error = await screen.findByText(/SERVER ERROR/i);
      expect(error).toBeInTheDocument();
    });
  });
});

我們可以使用waitFor的方式等待所有非同步事件完成並觸發callback,解釋如下

waitFor may run the callback a number of times until the timeout is reached. Note that the number of calls is constrained by the timeout and interval options.

This can be useful if you have a unit test that mocks API calls and you need to wait for your mock promises to all resolve.


上一篇
Day 15 使用renderHook
下一篇
Day 17 快沒文章了 先偷渡cypress 改天改寫一下
系列文
我不會測試,所以寫Jest與React Testing Library30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言