Search code examples
node.jsunit-testingjestjsnestjs

Nest can't resolve dependencies of the MyRepository in test cases nodejs


This is my repository

@Injectable()
export class MyRepository extends Repository<MyData> {
  constructor(private dataSource: DataSource) {
    super(MyData, dataSource.createEntityManager());
  }
}

and spec file's before each

beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [MyController],
      providers: [
        MyService,
        MyRepository ,

      ],
    }).compile();

but i am facing this

Nest can't resolve dependencies of the MyRepository (?). Please make sure that the argument DataSource at index [0] is available in the RootTestModule context.

Any help on this?


Solution

  • You need to create a mock for the DataSource provider. Honestly, you should be mocking anything that gets injected into the class you are testing, rather than adding it to the testing module for unit testing.

    {
      provide: DataSource,
      useValue: {
        createEntityManager: jest.fn(),
      }
    }