Search code examples
reactjsjestjsreact-testing-library

How to use constant imported from outside of test file (Jest, Reactjs)


I'm trying to check if a Button have a href value that is the same with what was defined in a const outside of the test file. The constants are formUrl and overviewUrl.

Anyone know how to solve this error? or is there another way to achieve what I want to?

import { cleanup, render } from "@testing-library/react";
import ComingSoon from "./page";
import { formUrl, overviewUrl } from "constant/urls";

// Note: running cleanup afterEach is done automatically for you in @testing-library/react@9.0.0 or higher
// unmount and cleanup DOM after the test is finished.
afterEach(cleanup);

it("Check if content is correct", () => {
  const { getByText } = render(<ComingSoon />);
  expect(
    getByText(
      "Be the first to know about our upcoming launch. Subscribe now for exclusive updates, sneak peeks, and special offers!"
    )
  ).toBeTruthy();
  expect(getByText("Remind me")).toBeTruthy();
  expect(getByText("Remind me").getAttribute("href")).toBe(formUrl);

  expect(getByText("Take me home")).toBeTruthy();
  expect(getByText("Take me home").getAttribute("href")).toBe(overviewUrl);
});
Test suite failed to run

    Cannot find module 'constant/urls' from 'app/coming-soon/page.test.tsx'

       6 | // unmount and cleanup DOM after the test is finished.
       7 | afterEach(cleanup);
    >  8 |
         | ^
       9 | it("Check if content is correct", () => {
      10 |   const { getByText } = render(<ComingSoon />);
      11 |   expect(

      at Resolver._throwModNotFoundError (../../node_modules/jest-resolve/build/resolver.js:427:11)
      at Object.<anonymous> (app/coming-soon/page.test.tsx:8:15)

Solution

  • Assuming the path is <Your Project Name>/src/contant/urls.ts and you want jest to recognize the path alias. Add moduleNameMapper configuration to the jest.config.js:

     moduleNameMapper: {
       '^constant/(.*)': '<rootDir>/src/constant/$1',
     },