当我在构造函数中测试需要一个参数的服务时,我必须使用对象将服务初始化为提供者,而不是简单地将服务作为提供者传递:
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.
只需在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
数组。