NestJs 与 Jest - 无法对原始值使用间谍操作

问题描述 投票:0回答:1

我在编写测试用例时遇到以下错误:

Cannot use spyOn on a primitive value; undefined given
代表线路
jest.spyOn(pipe.i18n,'getMessage').mockImplementation(()=>'Must be a valid number and greater than 0 (no decimals)' as never)

这是我的代码:

import { I18nCustomService } from '../../../utils/i18n-custom.service'

describe('ValidationPipe', () => {
  let pipe: ValidationPipe
  let i18n: I18nCustomService
  

  beforeEach(() => {
    pipe = new ValidationPipe(i18n)
  })

  describe('validateCustomHeader', () => {
    it('should throw exception for invalid tenant id', () => {
      const value = { tenantid: 'invalid' }
      jest.spyOn(pipe.i18n,'getMessage').mockImplementation(()=>'Must be a valid number and greater than 0 (no decimals)' as never)
      expect(() => pipe.validateCustomHeader(value)).toThrow(InvalidHttpHeadersException)
    })
  })
})
unit-testing jestjs internationalization nestjs-i18n
1个回答
0
投票

我探索并找到了问题的解决方案。 当尝试对未定义的对象的属性使用

jest.spyOn
时,会发生此错误。当试图监视其
pipe.i18n
方法时,似乎
undefined
getMessage

要解决此问题,请确保在尝试监视其方法之前正确初始化

i18n
。操作方法如下:

import { I18nCustomService } from '../../../utils/i18n-custom.service'
import { I18nService } from 'nestjs-i18n'

describe('ValidationPipe', () => {
  let pipe: ValidationPipe
  let i18n: I18nCustomService
  let i18nSrv: I18nService

  beforeEach(() => {
    i18n = new I18nCustomService(i18nSrv)
    pipe = new ValidationPipe(i18n)
  })

  describe('validateCustomHeader', () => {
    it('should throw exception for invalid id', () => {
      const value = { id: 'invalid' }
      expect(() => pipe.validateCustomHeader(value)).toThrow(InvalidHttpHeadersException)
    })
  })
})
© www.soinside.com 2019 - 2024. All rights reserved.