【问题标题】:How to test a service with multiple constructor parameters in NestJS如何在 NestJS 中测试具有多个构造函数参数的服务
【发布时间】:2019-03-03 18:14:36
【问题描述】:

背景

当我测试在构造函数中需要一个参数的服务时,我必须使用对象将服务初始化为提供者,而不是简单地将服务作为提供者传递:

auth.service.ts(示例)

@Injectable()
export class AuthService {

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

  // ...

}

auth.service.spec.ts(示例)

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


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

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

  // ...

})

请参阅this issue on GitHub了解此说明的来源。


我的问题

我有一个服务,在构造函数中需要 2 个参数:

auth.service.ts

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

  // ...

}

如何在测试环境中初始化此服务?我无法将多个值传递给providers 数组中的useValue。我的 AuthService 构造函数有 2 个参数,我需要同时传递它们才能使测试正常工作。

这是我当前(不工作)的设置:

auth.service.spec.ts

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

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [AuthService],
    }).compile()

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

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

  // ...

})

当我不传递它们时,我收到以下错误:

  ● AuthService › should be defined

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

【问题讨论】:

    标签: node.js typescript testing jestjs nestjs


    【解决方案1】:

    只需在providers 数组中为注入到AuthService 的构造函数中的每个提供程序创建一个条目:

    beforeEach(async () => {
      const module: TestingModule = await Test.createTestingModule({
        providers: [
          AuthService,
          {provide: JwtService, useValue: jwtServiceMock},
          {provide: AuthHelper, useValue: authHelperMock},
        ],
      }).compile()
    

    测试工具Test.createTestingModule() 创建一个与您的AppModule 一样的模块,因此也有一个providers 数组用于依赖注入。

    【讨论】:

      猜你喜欢
      • 2018-03-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-10
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      相关资源
      最近更新 更多