当我在构造函数中测试需要一个参数的服务时,我必须使用对象将服务初始化为提供者,而不是简单地通过提供者传递服务:
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,
) {}
// ...
}
如何在测试环境中初始化此服务?我无法将多个值传递给useValue
数组中的providers
。我的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.
答案 0 :(得分: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
数组用于依赖项注入。