How to unit test a class that uses inversifyjs to inject dependencies

483 Views Asked by At

I have inherited a react project that uses inversify ioc. It all works well but I'm having trouble writing unit tests. I'm sure my issue is caused by a problem in my configuration somewhere.

I'm getting this error when running the tests...

C:\xxx\src\app\services\auth\JWTAuthentication.service.ts:31 constructor(@(0, _inversify.inject)(_ICookieStorage.ICookieStorageService$) ^ SyntaxError: Invalid or unexpected token

So it seems to me that it can't resolve the @inject in my constructor...

constructor(@inject(ICookieStorageService$) cookieStorageService: ICookieStorageService) {
    ...code here
  }

In the root index.ts of my application, I wrap the application in

import { Provider } from 'inversify-react';
<Provider container={container}>
    ...the app
</Provider>

and container is defined in inversify.config.ts.

Obviously this doesn't get wired up when running tests. I'm not sure how to fix my issue. There is almost zero information out there on unit testing with inversify.

I've tried putting import 'reflect-metadata'; everywhere. That didn't help. Also, I don't use babel.

I must need to define a mock for the dependency. But no matter what I try, it doesn't seem to understand the @inject bit.

Please help if you can.

1

There are 1 best solutions below

0
On

Stuck up on this issue for a bit, but we was able to resolve this issue by following these steps:

  1. Install these packages
    npm install --save inversify-inject-decorators babel-plugin-transform-typescript-metadata
    
  2. Add babel-plugin-transform-typescript-metadata to your babel.config.js plugins array like this
    ...
    plugins: [
       ...,
       'babel-plugin-transform-typescript-metadata'
    ]
    ...
    
  3. Re-run your application.

Do try and let know if it works