如何在Jest测试文件中使用外部导入的常量(React项目)
我正尝试验证Button组件的href值是否与测试文件外部定义的常量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/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)
解决方案
先解决模块找不到的问题
- 核对文件路径:先确认
constant/urls对应的实际文件位置。如果constant文件夹不在Jest默认的模块搜索路径里,换成相对路径试试,比如你的测试文件在app/coming-soon/,如果constant在项目根目录的src下,就改成import { formUrl, overviewUrl } from "../../constant/urls";。 - 配置Jest路径别名:如果项目里用了绝对路径别名(比如
constant/xxx),需要在Jest配置文件里添加映射规则。打开jest.config.js(或jest.config.ts),加上:
moduleNameMapper: { '^constant/(.*)$': '<rootDir>/src/constant/$1', // 这里的路径要对应你项目里constant文件夹的实际位置 }
- 检查文件导出:确认
constant/urls文件里确实正确导出了formUrl和overviewUrl,比如:
export const formUrl = "/your-form-path"; export const overviewUrl = "/your-overview-path";
其他验证href的思路
如果不想纠结模块导入的问题,也可以换个方式验证:
- 直接验证实际路径值:不用导入常量,直接写死路径字符串来断言:
expect(getByText("Remind me").getAttribute("href")).toBe("/actual-form-path"); expect(getByText("Take me home").getAttribute("href")).toBe("/actual-overview-path");
- 模拟常量模块:用Jest的mock功能模拟
constant/urls的导出,这样既不用处理路径问题,也能验证组件正确使用了这些常量:
import * as urls from "constant/urls"; // 模拟模块导出 jest.mock("constant/urls", () => ({ formUrl: "/mock-form-url", overviewUrl: "/mock-overview-url", })); it("Check if content is correct", () => { const { getByText } = render(<ComingSoon />); // 验证组件使用了模拟的url expect(getByText("Remind me").getAttribute("href")).toBe(urls.formUrl); expect(getByText("Take me home").getAttribute("href")).toBe(urls.overviewUrl); });
内容的提问来源于stack exchange,提问作者jted95
相关产品推荐
相关产品推荐

