ReactTDD.com

Component mocks with React Testing Library

If you’re using React Testing Library, you can easily use the mocking techniques that are presented in Mastering React Test-Driven Development.

Look at the React test mocks cheatsheet you’ll see a run-down of all the ways that I end up testing component mocks in my code, sans-framework.

When you’re using React Testing Library, all the same ideas apply but you probably want to avoid building your own helpers if possible. So I suggest using data-testid for this purpose. The original form looked like this:

import { MyComponent } from "./MyComponent";
jest.mock("./MyComponent", () => ({
  MyComponent: jest.fn(() => <div id="MyComponent" />),
}));

With React Testing Library, you can use this instead:

import { MyComponent } from "./MyComponent";
jest.mock("./MyComponent", () => ({
  MyComponent: jest.fn(() => <div data-testid="MyComponent" />),
}));

Then you can test for the presence of a rendered component with this:

expect(screen.queryByTestId("MyComponent")).not.toBeNull();

Using data-testid is discouraged generally with React Testing Library, but it’s fine here because it exists only within your test. No application code is infected at all.

While we’re here, I might as well say that I generally prefer the query* versions of the React Testing Library functions over the get* versions, especially in a test where I’m checking for the presence of an element. No need for unnecessary exception throwing logic to complicate your test runs.

— Written by Daniel Irvine on August 27, 2022.