Olivier Van Bulck
Olivier Van Bulck

Reputation: 786

NestJS Error: Error: Nest can't resolve dependencies of the AuthService (?, JwtService)

I tried to test my Nest.js application for the first time. But when I tried to run it, almost every test which is created by the cli by default fails... I read about it being a problem with a database connection, so I tried using mongodb-memory-server, but it still won't work. Anyone here that knows how to fix this? As I'm creating a build pipeline it's very important that all tests succeed...

auth.service.ts

import { Injectable } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(private readonly usersService: UsersService, private jwtService: JwtService) {}

  async validateLoginUser(username: string, pass: string): Promise<any> {
    const user = await this.usersService.findByUsernameOrEmail(username);
    if (user && await user.comparePassword(pass)) {
      return user;
    }
    return null;
  }
  async validateFacebookUser(profile): Promise<any> {
    return await this.usersService.findByFacebookIdOrEmail(profile.id, profile.emails[0].value);
  }
  async validateJwtUser(payload): Promise<any> {
    return await this.usersService.findByJwtPayload(payload);
  }

  async login(user: any) {
    const payload = { username: user.username, sub: user.id };
    return {
      access_token: this.jwtService.sign(payload),
    };
  }
}

auth.service.spec.ts

import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';
import { MongooseModule } from '@nestjs/mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';

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

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [AuthService],
      imports: [
        PassportModule.register({defaultStrategy: 'jwt'}),
        JwtModule.register({secret: 'secret'}),
        MongooseModule.forRootAsync({
          useFactory: async () => {
            const mongod = new MongoMemoryServer();
            const uri = await mongod.getUri();
            return {
              uri,
            };
          },
        },
      )],
    }).compile();

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

  it('should be defined', () => {
    expect(service).toBeDefined();
  });
});

Error

Error: Nest can't resolve dependencies of the AuthService (?, JwtService). Please make sure that the argument at index [0] is available in the _RootTestModule context.

    at Injector.lookupComponentInExports (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/injector.js:183:19)
    at Injector.resolveComponentInstance (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/injector.js:143:33)
    at resolveParam (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/injector.js:96:38)
    at async Promise.all (index 0)
    at Injector.resolveConstructorParams (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/injector.js:112:27)
    at Injector.loadInstance (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/injector.js:78:9)
    at Injector.loadProvider (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/injector.js:35:9)
    at async Promise.all (index 3)
    at InstanceLoader.createInstancesOfProviders (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/instance-loader.js:41:9)
    at /home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/instance-loader.js:27:13
    at async Promise.all (index 1)
    at InstanceLoader.createInstances (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/instance-loader.js:26:9)
    at InstanceLoader.createInstancesOfDependencies (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/core/injector/instance-loader.js:16:9)
    at TestingModuleBuilder.compile (/home/olivier/Projects/bp/bp-website-back-nest/node_modules/@nestjs/testing/testing-module.builder.js:38:9)

Upvotes: 0

Views: 1392

Answers (2)

user20183324
user20183324

Reputation: 1

Ensure you add the the userService in the Users.module.ts export as shown in the image his exposes he user service to the ohe module

Image o he uses.module.ts

Upvotes: -3

leonardfactory
leonardfactory

Reputation: 3501

In Nest.js, all the needed Providers should be available when creating an instance of a Provider. In this case you're creating a test module, however UserService:

  1. Is not exported from any of the modules you're importing (it is clear just because they're third-party modules, not domain ones)
  2. It is not defined in providers array

So Nest.js is telling you it can't find the Provider anywhere.

Adding it to providers like [AuthService, UserService] (and others if necessary) should make Nest.js able to find it, load it and then providing you your service.

Upvotes: 2

Related Questions