nv.snow
nv.snow

Reputation: 934

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

I have an app that fetches a list of users and displays them. The app works as expected but the test fails:

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;

I've setup MSW using the steps outlined here.

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();
});

What am I missing? The output of the test render doesn't show the mock response data.

TestingLibraryElementError: Unable to find an element with the text: Xavi Alonzo

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

Upvotes: 3

Views: 2488

Answers (1)

nv.snow
nv.snow

Reputation: 934

There are two problems in Users.test.js

  1. Need to add async/await
  2. Use findByText instead of getByText

With these changes, the test passes:

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

Look at the documentation for the difference between getBy... and findBy...

Upvotes: 2

Related Questions