React 测试库 - 组件未使用模拟 Service Worker 响应

React Testing Library - Mock Service Worker response not used by component

我有一个应用程序可以获取用户列表并显示它们。该应用程序按预期运行但测试失败:

Users.js

import React from 'react';

function Users() {
  const [users, setUsers] = React.useState([]);

  React.useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json())
      .then(data => setUsers(data))
  }, [])

  return (
    <div>
      {users.map(user => {
        return (
          <h3 key={user.id}>{user.name}</h3>
        )
      })}
    </div>
  );
}

export default Users;

我已经使用 steps outlined here 设置了 MSW。

handlers.js

import { rest } from 'msw';

export const handlers = [
  rest.get('https://jsonplaceholder.typicode.com/users', (req, res, ctx) => {
    return res(
      ctx.json([
        { id: 1, name: 'Xabi Alonzo' },
        { id: 2, name: 'Lionel Messi' }
      ])
    )
  })
];

server.js

import { setupServer } from 'msw/node';
import { handlers } from './handlers';

export const server = setupServer(...handlers);

setupTests.js

import '@testing-library/jest-dom';
import { server } from './mocks/server.js';

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

Users.test.js

import { render, screen } from '@testing-library/react';
import Users from './Users';

test('Renders a list of users', () => {
  render(<Users />);
  const text = screen.getByText('Xavi Alonzo');
  expect(text).toBeInTheDocument();
});

我错过了什么?测试渲染的输出不显示模拟响应数据。

TestingLibraryElementError:无法找到包含文本的元素:Xavi Alonzo

<body>
  <div>
    <div />
  </div>
</body>

Users.test.js有两个问题

  1. 需要加上async/await
  2. 使用 findByText 而不是 getByText

经过这些更改,测试通过:

test('Renders a list of users', async () => {
  render(<Users />);
  const text = await screen.findByText('Xabi Alonzo');
  expect(text).toBeInTheDocument();
});

查看 documentation 了解 getBy...findBy...[=12= 之间的区别]