Search code examples
typescriptjestjsreact-testing-librarytesting-library

How to add '@testing-library/jest-dom' globally?


I saw in a project using create-react-app a file named setupTest.js which just imports @testing-library/jest-dom and the tests seems to use the extented expect version, like .toBeInTheDocument.

I added the same file (setupTest.js) to my project but seems to be no effect.

In other words, how can I import @testing-library/jest-dom globally instead of doing in every .spec.ts file?


Solution

  • Create a jest.config.js file and add setupFilesAfterEnv property to it and configure it to your setupTests.js file address like this:

    module.exports = {
      setupFilesAfterEnv: ["<rootDir>/app/config/setupTests.js"],
    };
    

    and then in your setupTests.js add this code:

    import "@testing-library/jest-dom/extend-expect";