14

I'm developing an application using dependency injection with tsyringe. That's the example of a service that receives the repository as a dependency:

import { injectable, inject } from 'tsyringe'

import IAuthorsRepository from '@domains/authors/interfaces/IAuthorsRepository'

@injectable()
export default class ListAuthorsService {
  constructor (
    @inject('AuthorsRepository')
    private authorsRepository: IAuthorsRepository
  ) {}

And the dependencies container:

import { container } from 'tsyringe'

import IAuthorsRepository from '@domains/authors/interfaces/IAuthorsRepository'
import AuthorsRepository from '@domains/authors/infra/typeorm/repositories/AuthorsRepository'

container.registerSingleton<IAuthorsRepository>(
  'AuthorsRepository',
  AuthorsRepository
)

export default container

In the tests, I don't want to use the dependencies registered on the container, but instead, to pass a mock instance via parameter.

let authorsRepository: AuthorsRepositoryMock
let listAuthorsService: ListAuthorsService

describe('List Authors', () => {
  beforeEach(() => {
    authorsRepository = new AuthorsRepositoryMock()
    listAuthorsService = new ListAuthorsService(authorsRepository)
  })

But I'm receiving the following error:

tsyringe requires a reflect polyfill. Please add 'import "reflect-metadata"' to the top of your entry point.

What I thought was - "I may need to import the reflect-metadata package before executing the tests". So I created a jest.setup.ts which imports the reflect-metadata package. But another error occurs:

Error

The instance of the repository is somehow undefined.

I would like to run my tests in peace.

Laura Beatris
  • 1,782
  • 7
  • 29
  • 49

2 Answers2

28

First create in root of your project an jest.setup.ts.

In your jest.config.js, search for this line:

// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],

uncomment, and add your jest.setup.ts file path.

// A list of paths to modules that run some code to configure or set up the testing framework before each test
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],

Now import the reflect-metadata in jest.setup.ts:

import 'reflect-metadata';

And run tests again.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Ebert Mota
  • 281
  • 3
  • 3
0

I went through the same problem here and refactoring the test find out that it has to import the dependencies first and then the class of service that will be tested

Dharman
  • 30,962
  • 25
  • 85
  • 135