React testing library using beforeAll to render cannot find item on 2nd test

Viewed 1257

The first tests passes.

The 2nd one I get error:

import React from 'react';
import { render, fireEvent, waitFor, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom/extend-expect';

import WrapProvider from '__tests__/__utils__/WrapProvider';

import PageMovies from 'src/pages/movies/index';
import { dataTestid as dataTestIdMoviesCount } from 'src/components/Specific/Movies/MoviesCount';
import { dataTestid as dataTestidDropdown } from 'src/components/Specific/Movies/SearchMovies/DropdownMovieGenres';

describe('<PageMovies>', () => {
  beforeAll(async () => {
    render(
      <WrapProvider>
        <PageMovies />
      </WrapProvider>
    );
    await waitFor(() => screen.getByTestId(dataTestIdMoviesCount)); // success
  });
  describe('onload', () => {
    it('Should have search results', () => {
      expect(screen.getByTestId(dataTestIdMoviesCount)).toHaveTextContent(/ [1-9]/); //success
    });
  });
  describe('dropdown and search', () => {
    it('Should have dropdown', () => {
      const $dropdown = screen.getByTestId(dataTestidDropdown); // <- error - not found.
      // userEvent.selectOptions(screen.getByTestId(dataTestidDropdown), '28');
      // expect((screen.getByLabelText('Action') as HTMLOptionElement).selected).toBeTruthy();
    });
  });
});

error: TestingLibraryElementError: Unable to find an element by: [data-testid="movies-dropdown"]

Yet this element does exist on the page onload

<div name="genre" style="width:400px" data-testid="movies-dropdown" role="combobox" aria-expanded="false" class="ui compact fluid multiple search selection dropdown">

Am I using screen.getByTestId correctly? It seems there are 3 ways to use this. Which is the right way?

  • import { getByTestId } from '@testing-library/react';
  • const { getByTestId } = render(<MyComponent/>);
  • import { screen } from '@testing-library/react'; screen.getByTestId()
2 Answers

Perhaps dropdown is not appearing on initial load, you could findByTestId (which is a promise which searches for 1000ms)

Ideally you want to use the returned function from render(). There are a few exceptions such as when a React.portal is used.

In fact, you want to refrain from using data-testid, it's best to search through what a user can access, such as accessibility roles/name and text.

Related