NX Monorepo运行Lib测试时出现ReferenceError: jest is not defined错误
NX Monorepo中Lib测试出现
ReferenceError: jest is not defined的解决方法 问题场景
在NX Monorepo的Lib中运行测试时遇到以下问题:
- 初始阶段无法找到Jest相关类型,添加
/// <reference types="@types/jest" />后类型问题得到解决 - 运行测试时却抛出
ReferenceError: jest is not defined错误 - Jest已安装在Monorepo根目录,尝试过为该Lib单独安装Jest、删除node_modules重新安装,均未解决问题
测试代码如下:
/// <reference types="@types/jest" /> import { handleTokenAuthorization } from '.'; describe('auth funtions', () => { it('Should mount and replace url correctly to login screen', () => { const url = `${process.env.NX_APP_CLIENT_ID}/authorize?response_type=code&client_id=${process.env.NX_FRONT_URL}&scope=openid+profile&redirect_uri=${process.env.VITE_FRONT_URL}/receive-auth-token`; const replaceFn = jest.spyOn(window.location, 'replace'); handleTokenAuthorization(); expect(replaceFn).toBeCalledWith(url); }); });
解决方案
- 检查Lib的Jest配置文件:确保Lib目录下的
jest.config.ts(或jest.config.js)正确继承根目录配置,且启用全局变量注入。示例配置:import { getJestProjects } from '@nx/jest'; export default { projects: getJestProjects(), globals: { 'ts-jest': { tsconfig: '<rootDir>/tsconfig.spec.json', }, }, }; - 验证TS测试配置:检查Lib的
tsconfig.spec.json,确认compilerOptions.types中包含jest:{ "extends": "./tsconfig.json", "compilerOptions": { "types": ["jest", "node"] }, "include": ["**/*.spec.ts", "**/*.spec.tsx", "**/*.spec.js", "**/*.spec.jsx"] } - 使用NX官方命令运行测试:不要直接调用
jest命令,改用nx test <你的Lib名称>执行测试,确保加载Monorepo全局配置和共享依赖。 - 统一安装依赖:在Monorepo根目录执行
npm install或yarn install,NX会自动处理依赖共享,无需单独给Lib安装Jest,单独安装可能引发版本冲突。 - 手动注入全局变量:如果项目使用Vite+NX组合,可在Lib的
setupFilesAfterEnv配置文件中添加全局导入:import '@jest/globals';
内容的提问来源于stack exchange,提问作者niltonxp
相关产品推荐
相关产品推荐

