unit-testingjestjsinternationalizationnestjs-i18n

NestJs with Jest - Cannot use spyOn on a primitive value


I am getting the below error while writing test cases: Cannot use spyOn on a primitive value; undefined given for line jest.spyOn(pipe.i18n,'getMessage').mockImplementation(()=>'Must be a valid number and greater than 0 (no decimals)' as never)

Here are my codes:

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)
    })
  })
})

Solution

  • I explored and got the solution of the issue. This error occurs when trying to use jest.spyOn on a property of an object that is undefined. It seems pipe.i18n is undefined when attempting to spy on its getMessage method.

    To resolve this issue, ensure that i18n is properly initialized before trying to spy on its methods. Here's how to do it:

    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)
        })
      })
    })