Search code examples
typescriptjestjsinstanceofts-jest

Jest and Typescript: Unable to check if object is instance of class


I need to check if the method is returning an instance of a class, but I'm kinda lost here. I'm getting a ReferenceError when I run the tests.

Mapper.spec.js:

import { SetConfigurationRequestModel } from '../../usecases/Models/SetConfigurationRequestModel'
import { ISetConfigurationRequest } from '../requests/ISetConfigurationRequest'
import { Mapper } from './Mapper'

describe('Helpers/Mappers', () => {
  describe('cfgRequest2RequestModel', () => {
    test('should exist', () => {
      const sut = new Mapper()
      expect(sut.cfgRequest2RequestModel).toBeTruthy()
    })
    test('should be a method', () => {
      const sut = new Mapper()
      expect(typeof sut.cfgRequest2RequestModel).toBe('function')
    })
    test('should return a RequestModel', () => {
      const sut = new Mapper()
      const fakeRequest = makeFakeRequest()
      const requestModel = sut.cfgRequest2RequestModel(fakeRequest)
      expect(requestModel).toBeInstanceOf(SetConfigurationRequestModel)
    })
  })
})

Mapper.js:

import { SetConfigurationRequestModel } from '../../usecases/Models/SetConfigurationRequestModel'
import { ISetConfigurationRequest } from '../requests/ISetConfigurationRequest'

export class Mapper {
  cfgRequest2RequestModel (request: ISetConfigurationRequest): object {
    const request2 = new SetConfigurationRequestModel()
    return request2
  }
}


jest output:

FAIL  src/delivery/helpers/mappers.spec.ts
  ● Helpers/Mappers › cfgRequest2RequestModel › should return a RequestModel

    ReferenceError: SetConfigurationRequestModel is not defined

      4 | export class Mapper {
      5 |   cfgRequest2RequestModel (request: ISetConfigurationRequest): object {
    > 6 |     const request2 = new SetConfigurationRequestModel()
        |                      ^
      7 |     return request2
      8 |   }
      9 | }

      at Mapper.cfgRequest2RequestModel (src/delivery/helpers/Mapper.ts:6:22)
      at Object.<anonymous> (src/delivery/helpers/mappers.spec.ts:42:32)```

Solution

  • The problem is not code related.

    Just in case somebody goes through the same, add --no-cache options to jest command.