question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. ItΒ collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unable to run tests because Nest can't resolve dependencies of a service

See original GitHub issue

I’m submitting a…


[ ] Regression 
[ ] Bug report
[ ] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

I have followed the unit test example but I am unable to get my very simple test to run (it’s literally just testing if true === true) but it won’t work because I’m met with this error

Nest can't resolve dependencies of the RoleService (?). Please verify whether [0] argument is available in the current context.

Minimal reproduction of the problem with instructions

You can find the repo at https://bitbucket.org/mogusbi/breeze-bb/

After cloning, run npm run api:test

// role.controller.spec.ts
import {Test} from '@nestjs/testing';
import {TestingModule} from '@nestjs/testing/testing-module';
import {RoleController} from './role.controller';
import {RoleService} from './role.service';

describe('Role controller', () => {
  let controller: RoleController;
  let service: RoleService;

  beforeEach(async () => {
    const mod: TestingModule = await Test
      .createTestingModule({
        components: [
          RoleService
        ],
        controllers: [
          RoleController
        ]
      })
      .compile();

    controller = mod.get<RoleController>(RoleController);
    service = mod.get<RoleService>(RoleService);
  });

  it('should be true', () => {
    expect(true).toBe(true);
  });
});

// role.controller.ts
import {Controller} from '@nestjs/common';
import {RoleService} from './role.service';

@Controller('role')
export class RoleController {
  constructor (
    private readonly roleService: RoleService
  ) {}

  ...
}

// role.service.ts
import {InjectModel} from '@nestjs/mongoose';
import {PaginateModel} from 'mongoose';
import {IRole} from './role.interface';
import {RoleSchema} from './role.schema';

@Component()
export class RoleService {
  constructor (
    @InjectModel(RoleSchema) private readonly model: PaginateModel<IRole>
  ) {}

  ...
}

Environment


- Node version: 8.2.1
- Platform:  Mac OS 10.13.2

β”œβ”€β”€ @nestjs/common@4.5.9
β”œβ”€β”€ @nestjs/core@4.5.9
β”œβ”€β”€ @nestjs/mongoose@2.0.0
β”œβ”€β”€ @nestjs/swagger@1.1.3
β”œβ”€β”€ @nestjs/testing@4.5.5
β”œβ”€β”€ @types/body-parser@1.16.8
β”œβ”€β”€ @types/express@4.11.0
β”œβ”€β”€ @types/jest@22.0.1
β”œβ”€β”€ @types/mongoose@4.7.32
β”œβ”€β”€ @types/mongoose-paginate@5.0.6
β”œβ”€β”€ @types/morgan@1.7.35
β”œβ”€β”€ @types/node@8.5.8
β”œβ”€β”€ body-parser@1.18.2
β”œβ”€β”€ class-transformer@0.1.8
β”œβ”€β”€ class-validator@0.7.3
β”œβ”€β”€ jest@22.0.6
β”œβ”€β”€ mongoose@4.13.9
β”œβ”€β”€ mongoose-paginate@5.0.3
β”œβ”€β”€ morgan@1.9.0
β”œβ”€β”€ nodemon@1.14.11
β”œβ”€β”€ reflect-metadata@0.1.10
β”œβ”€β”€ rxjs@5.5.6
β”œβ”€β”€ ts-jest@22.0.1
β”œβ”€β”€ ts-node@4.1.0
β”œβ”€β”€ tslint@5.9.1
β”œβ”€β”€ tslint-eslint-rules@4.1.1
β”œβ”€β”€ tslint-microsoft-contrib@5.0.1
└── typescript@2.6.2

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:5
  • Comments:53 (9 by maintainers)

github_iconTop GitHub Comments

27reactions
pterblghcommented, May 29, 2018

Hey guys!

I’ve read the testing part of the database documentation but I could not find any hint or best practice for creating the mockRepository object.

I would like to write tests where I mock the database layer of the service (e.g.: the adminRepository of the AuthService) by providing good ol’ POJOs as data source. Is this achievable with the current version of TypeORM / Nest?

There is a related conversation in typeorm/typeorm#1267, but I couldn’t get closer to my desired functionality.

My AuthService looks like this:

// auth.service.ts

@Injectable()
export class AuthService {

  constructor(
    @InjectRepository(Admin)
    private readonly adminRepository: Repository<Admin>,
  ) { }

  findByEmail(email: string): Promise<Admin> {
    return this.adminRepository.findOne({ where: { email } });
  }

  findById(id: number): Promise<Admin> {
    return this.adminRepository.findOne(id);
  }

}

The desired output would look like something like this:

// auth.service.spec.ts

describe('AuthService', () => {
  let authService: AuthService;

  const mockRepository = {
    data: [
      { id: 1, email: 'test1@email.com', password: '' },
      { id: 2, email: 'valid@email.com', password: '' },
    ],
  };

  beforeEach(async () => {
    const module = await Test.createTestingModule({
        providers: [
          AuthService,
          {
            provide: getRepositoryToken(Admin),
            useValue: mockRepository,
          },
        ],
      }).compile();

    authService = module.get<AuthService>(AuthService);
  });

  describe('findByEmail', () => {
    it('should return an Admin with a valid email', async () => {
      const email = 'valid@email.com';
      const expected = mockRepository.data[1];
      const admin = await authService.findByEmail(email);
      expect(admin).toBe(expected);
    });
  });

});

I really look forward to hear some advices and tips about the pros/cons of this kind of testing strategy, my primary goal is to keep my unit tests as simple and as fast as I can. I really appreciate any help!

19reactions
VinceOPScommented, Feb 3, 2018

For people encoutering the same error message with TypeORM, please note that the DI loader cannot β€œknow” your Repository instances as they’re injected with @InjectRepository:

export class DogsService {
  constructor(@InjectRepository(Dog) private readonly dogsRepository: Repository<Dog>) {
    // ...
  }
}

I had more or less the same issue this morning and solved it by injecting β€œDogsRepository” manually:

Test.createTestingModule({
  components: [
    {
      provide: 'DogsRepository',
      useClass: Repository,
    }
  ],
  // ...
}).compile();

However, I would recommend extending Repository<Dog> with a custom repo Class (class DogsRepository extends Repository<Dog>) and use it in useClass (useClass: DogsRepository, instead of useClass: Repository), in order to be able to test the type of values returned by the repository instance (if you need to).

@kamilmysliwiec: does everything sound correct? Or am I mistaken somewhere? Shall I add it do the documentation?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Nest can't resolve dependencies in the RootTestModule ...
I have a nestjs project contains multiple apps and libs. When I run the test yarn jest --config ./jest.config.json libs/lib1 , it worksΒ ......
Read more >
Common errors - FAQ - A progressive Node.js framework
"Cannot resolve dependency" error#. Probably the most common error message is about Nest not being able to resolve dependencies of a provider. The...
Read more >
Nest can't resolve dependencies of the UsersService ... - Reddit
I did a small NestJs App with v9 and I'm getting this error. I can save my data in mi sqlite db, but...
Read more >
nest can't resolve dependencies of the httpservice - You.com
I would like this module to provide a new HTTP service per request? problems that I am facing: When I try to add...
Read more >
NestJS: Resolving Dependency Injection - Tevpro
Resolving a dependency inject issue in NestJS by changing the order of the files referenced ... Nest can't resolve dependencies of the AuthController...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found