如何使用从测试文件外部导入的常量(Jest、Reactjs)

问题描述 投票:0回答:1

我正在尝试检查按钮的

href
值是否与测试文件外部的
const
中定义的值相同。常数为
formUrl
overviewUrl

有人知道如何解决这个错误吗?或者还有其他方法可以实现我想要的吗?

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/[email protected] 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)
reactjs jestjs react-testing-library
1个回答
0
投票

假设路径是

src/contant/urls.ts
并且您希望 jest 识别路径别名。将
moduleNameMapper
配置添加到
jest.config.js
:

 moduleNameMapper: {
   '^constant/(.*)': '<rootDir>/src/constant/$1',
 },
© www.soinside.com 2019 - 2024. All rights reserved.