使用Jest测试NestJS时遇报错:Cannot use spyOn on a primitive value
解决NestJS测试中"Cannot use spyOn on a primitive value; undefined given"报错
报错原因
你代码里的i18n变量仅声明未初始化,beforeEach中直接将undefined的i18n传入ValidationPipe构造函数,导致pipe.i18n为undefined。而jest.spyOn无法对undefined执行间谍操作,因此触发该报错。
解决方案
初始化模拟的I18nCustomService实例
在beforeEach中创建I18nCustomService的模拟对象,确保i18n是一个有效的对象实例,再传入ValidationPipe。mock目标方法
直接在模拟的i18n对象上mockgetMessage方法,无需通过pipe.i18n执行spy操作(也可选择spyOn已初始化的模拟对象)。
修正后完整代码示例
import { I18nCustomService } from '../../../utils/i18n-custom.service' import { ValidationPipe } from './your-validation-pipe-path'; // 替换为实际文件路径 import { InvalidHttpHeadersException } from './your-exception-path'; // 替换为实际文件路径 describe('ValidationPipe', () => { let pipe: ValidationPipe; let i18n: I18nCustomService; beforeEach(() => { // 创建模拟的I18nCustomService实例 i18n = { getMessage: jest.fn() } as unknown as I18nCustomService; pipe = new ValidationPipe(i18n); }); describe('validateCustomHeader', () => { it('should throw exception for invalid tenant id', () => { const value = { tenantid: 'invalid' }; // mock getMessage方法的返回值 i18n.getMessage.mockReturnValue('Must be a valid number and greater than 0 (no decimals)' as never); expect(() => pipe.validateCustomHeader(value)).toThrow(InvalidHttpHeadersException); }); }); });
内容的提问来源于stack exchange,提问作者Shubham Verma
相关产品推荐
相关产品推荐

