The error you're encountering indicates that the @testing-library/jest-dom/extend-expect module is missing from your project. This module provides additional custom Jest matchers that are useful for testing DOM elements in React applications. To resolve this issue, follow the steps below:
1. Install @testing-library/jest-dom
First, you need to install the @testing-library/jest-dom package as a development dependency. This package extends Jest with custom matchers for the DOM.
Using npm:
npm install --save-dev @testing-library/jest-dom
Using yarn:
yarn add --dev @testing-library/jest-dom
2. Update Your Test Setup
There are two common ways to include @testing-library/jest-dom in your tests:
A. Import Directly in Each Test File
If you prefer to import the matchers in each test file individually, you can adjust your import statement slightly. In recent versions of @testing-library/jest-dom, you no longer need to specify the /extend-expect path.
Update your import statement in projectSearch.test.js as follows:
import "@testing-library/jest-dom";
Updated Test File (projectSearch.test.js):
import React from "react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import "@testing-library/jest-dom"; // Updated import
import { Provider } from "react-redux";
import configureMockStore from "redux-mock-store";
import thunk from "redux-thunk";
import ProjectSearch from "./ProjectSearch";
import { fetchSearchItems } from "../../store/actions/actions";
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
jest.mock("../../store/actions/actions", () => ({
fetchSearchItems: jest.fn(),
}));
describe("ProjectSearch Component", () => {
let store;
beforeEach(() => {
store = mockStore({
search: { searchTerm: "" },
});
});
it("renders search input field", () => {
render(
<Provider store={store}>
<ProjectSearch />
</Provider>
);
const inputElement = screen.getByPlaceholderText("Search articles...");
expect(inputElement).toBeInTheDocument();
});
it("dispatches fetchSearchItems when typing in the search input", async () => {
render(
<Provider store={store}>
<ProjectSearch />
</Provider>
);
const inputElement = screen.getByPlaceholderText("Search articles...");
fireEvent.change(inputElement, { target: { value: "React" } });
await waitFor(() => {
expect(fetchSearchItems).toHaveBeenCalledWith("React");
});
});
});
B. Configure Jest to Automatically Include jest-dom
If you want to include @testing-library/jest-dom in all your test files automatically, you can configure Jest to use a setup file.
-
Create a Jest Setup File
Create a file named jest.setup.js (or any name you prefer) in your project root or a designated configuration directory.
jest.setup.js:
import "@testing-library/jest-dom";
-
Update Jest Configuration
Ensure that Jest is aware of the setup file. You can do this by adding the setupFilesAfterEnv property in your jest.config.js or directly in your package.json under the jest section.
If using jest.config.js:
// jest.config.js
module.exports = {
// ...other configurations
setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
};
If configuring in package.json:
{
// ... other package.json settings
"jest": {
// ...other Jest settings
"setupFilesAfterEnv": ["<rootDir>/jest.setup.js"]
}
}
Note: Replace "<rootDir>/jest.setup.js" with the correct path to your setup file if it's located elsewhere.
-
Remove Direct Imports from Test Files
Since the setup file automatically includes @testing-library/jest-dom, you can remove the direct import from your test files.
Updated Test File Without Direct Import:
import React from "react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { Provider } from "react-redux";
import configureMockStore from "redux-mock-store";
import thunk from "redux-thunk";
import ProjectSearch from "./ProjectSearch";
import { fetchSearchItems } from "../../store/actions/actions";
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
jest.mock("../../store/actions/actions", () => ({
fetchSearchItems: jest.fn(),
}));
describe("ProjectSearch Component", () => {
let store;
beforeEach(() => {
store = mockStore({
search: { searchTerm: "" },
});
});
it("renders search input field", () => {
render(
<Provider store={store}>
<ProjectSearch />
</Provider>
);
const inputElement = screen.getByPlaceholderText("Search articles...");
expect(inputElement).toBeInTheDocument();
});
it("dispatches fetchSearchItems when typing in the search input", async () => {
render(
<Provider store={store}>
<ProjectSearch />
</Provider>
);
const inputElement = screen.getByPlaceholderText("Search articles...");
fireEvent.change(inputElement, { target: { value: "React" } });
await waitFor(() => {
expect(fetchSearchItems).toHaveBeenCalledWith("React");
});
});
});
3. Verify Your Setup
After completing the steps above, run your tests again:
npm run test
or
yarn test
The tests should now recognize the @testing-library/jest-dom matchers and pass without the Cannot find module error.
4. Additional Recommendations
-
Check Package Versions: Ensure that all testing libraries are up-to-date to avoid compatibility issues.
-
Use screen Wisely: You're already using screen, which is recommended for cleaner and more readable tests.
-
Mocking Redux Store: Continue using redux-mock-store and thunk as you've set up for dispatching actions in your tests.
5. Final Thoughts
Using @testing-library/jest-dom enhances the readability and expressiveness of your tests by providing intuitive matchers like toBeInTheDocument(). Properly setting up your testing environment ensures smoother test development and maintenance.
If you encounter further issues or have additional questions, feel free to ask!