NestJS 错误:错误:Nest 无法解析 AuthService (?, JwtService) 的依赖项

Posted

技术标签:

【中文标题】NestJS 错误:错误:Nest 无法解析 AuthService (?, JwtService) 的依赖项【英文标题】:NestJS Error: Error: Nest can't resolve dependencies of the AuthService (?, JwtService) 【发布时间】:2020-08-12 14:53:58 【问题描述】:

我第一次尝试测试我的 Nest.js 应用程序。但是当我尝试运行它时,几乎所有由 cli 默认创建的测试都失败了......我读到它是数据库连接的问题,所以我尝试使用 mongodb-memory-server,但它仍然不会不工作。这里有谁知道如何解决这个问题?在我创建构建管道时,所有测试都成功非常重要...

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: 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)

【问题讨论】:

请添加您的AuthService 定义 我添加了 AuthService 定义 【参考方案1】:

在 Nest.js 中,所有需要的 Provider 在创建 Provider 实例时都应该可用。在这种情况下,您正在创建一个测试模块,但是 UserService:

    不会从您importing 的任何模块中导出(很明显,因为它们是第三方模块,而不是域模块) providers数组中没有定义

所以 Nest.js 告诉你它在任何地方都找不到 Provider。

将它添加到providers,如[AuthService, UserService](如有必要,还可以添加其他)应该使 Nest.js 能够找到它、加载它,然后为您提供服务。

【讨论】:

以上是关于NestJS 错误:错误:Nest 无法解析 AuthService (?, JwtService) 的依赖项的主要内容,如果未能解决你的问题,请参考以下文章

NestJS / TypeOrm / Neo4j :Nest 无法解析 NEO4J_DRIVER 的依赖关系

NestJS 缺少依赖

Nest 无法解析 PhotoService 的依赖关系(?)

Nest 无法解析存储库的依赖关系

升级到7后,Nestjs无法启动。

e2e 如何与 guard nestjs