You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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执行间谍操作,因此触发该报错。

解决方案

  1. 初始化模拟的I18nCustomService实例
    在beforeEach中创建I18nCustomService的模拟对象,确保i18n是一个有效的对象实例,再传入ValidationPipe。

  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 21:50:07