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:
The instance of the repository is somehow undefined.
I would like to run my tests in peace.