如何在 NestJS 中测试具有多个构造函数参数的服务

Jac*_*cob 4 testing node.js typescript jestjs nestjs

背景

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

auth.service.ts(示例)

@Injectable()
export class AuthService {

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

  // ...

}
Run Code Online (Sandbox Code Playgroud)

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

  // ...

})
Run Code Online (Sandbox Code Playgroud)

有关此解释的来源,请参阅GitHub 上的此问题


我的问题

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

auth.service.ts

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

  // ...

}
Run Code Online (Sandbox Code Playgroud)

如何在测试环境中初始化这个服务?我无法useValueproviders数组中传递多个值。我的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()
  })

  // ...

})
Run Code Online (Sandbox Code Playgroud)

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

  ? 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.
Run Code Online (Sandbox Code Playgroud)

Kim*_*ern 8

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

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

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