使用Jest全局变量名作为顶级标识符致测试报错的解决咨询
解决Jest全局变量与被测代码
const jest冲突的方案 针对单个测试文件解决冲突,不修改被测代码且不影响其他测试,有以下两种可行方案:
方案一:临时重命名/删除全局jest变量(无需修改Jest全局配置)
在目标测试文件中,先保存全局的jest变量,删除后再引入被测模块,最后恢复全局变量,保证后续测试正常使用Jest API:
// 保存全局jest变量 const originalJest = global.jest; // 删除全局jest,避免与被测代码的const jest冲突 delete global.jest; // 引入被测模块 const eslintConfig = require('../eslint.config.js'); // 恢复全局jest,确保测试中能正常使用Jest的API global.jest = originalJest; describe('ESLint config', () => { test('should ban correct imports for JS files', () => { // 编写你的测试逻辑 expect(eslintConfig.rules).toHaveProperty('import/no-restricted-paths'); }); });
方案二:为单个测试文件单独配置injectGlobals: false
通过Jest的多项目配置,为目标测试文件单独禁用全局jest注入,其他测试保持默认配置:
- 修改
jest.config.js,添加一个针对目标测试文件的子项目配置:
module.exports = { // 全局默认配置 testEnvironment: 'node', // 多项目配置 projects: [ { displayName: 'default', // 匹配所有除目标文件外的测试 testPathIgnorePatterns: ['**/__tests__/eslint-config.test.js'], }, { displayName: 'no-jest-global', // 仅匹配目标测试文件 testMatch: ['**/__tests__/eslint-config.test.js'], // 禁用全局jest变量注入 injectGlobals: false, }, ], };
- 在目标测试文件中,手动导入Jest所需的API(因为禁用了全局注入):
// 手动导入Jest的测试API const { describe, test, expect } = require('@jest/globals'); const eslintConfig = require('../eslint.config.js'); describe('ESLint config', () => { test('should ban correct imports for JS files', () => { // 测试逻辑 }); });
这两种方案都能避免修改被测代码,且仅影响目标测试文件,不会干扰其他测试的正常运行。
内容的提问来源于stack exchange,提问作者Alexey Romanov
相关产品推荐
相关产品推荐

