0

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

用户.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;

我已经使用此处列出的步骤设置了 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' }
      ])
    )
  })
];

服务器.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());

用户.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>
4

1 回答 1

0

Users.test.js 有两个问题

  1. 需要添加异步/等待
  2. 使用findByText而不是 getByText

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

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

查看文档以了解getBy...findBy...之间的区别

于 2022-01-23T06:48:10.090 回答