reflect-metadata TypeError when running a unit test using HEST

69 views Asked by At
  • I have a service class that is utilising TypeDI
  • Trying to write and run some unit tests for this service but getting the following error

enter image description here

Most of the research I've done suggests making sure that

import 'reflect-metadata';

comes before anything else. So I added jest.setup.ts file and my JEST configuration has the following entries

{
..
setupFilesAfterEnv: ['<rootDir>/tests/jest.setup.ts'],
setupFiles: ['reflect-metadata']
..
}

I put some console logs inside my jest.setup.ts and I can see them printed so it's definitely being used.

The error, however, persists. Any suggestions much appreciated.

1

There are 1 answers

0
nlv On

Ok, after much deliberation with myself, I found the issue:

my service constructor had some questionable (?) variable injection signature e.g.:

constructor(@Inject("p1") p1: string = "localhost", 
    @Inject("p2") p2: number = 5556, 
    @Inject("p3") p3: number = 9283) {

...
}

After reading more documentation on how to create services that require constructor parameters, refactoring the service constructor signature fixed the issue (removed direct variable injection and left it as normal parameters).