我有两个 Mock 服务:
@Injectable()
class UserRegistrationServiceMock {
registerBasicDetails(details: UserRegistrationDetails) {
let response: UserRegistrationResponse = new UserRegistrationResponse();
response.success = false;
response.userMessage = 'Test Message';
return Observable.of(response);
}
registerAdvancedDetails() {
}
}
@Injectable()
class UserRegistrationServiceSuccessMock {
registerBasicDetails(details: UserRegistrationDetails) {
let response: UserRegistrationResponse = new UserRegistrationResponse();
response.success = true;
response.userMessage = 'Test Message';
return Observable.of(response);
}
registerAdvancedDetails() {
}
}
在我的 Jasmine 测试中,我在“beforeEachProviders”和“beforeEach”方法中提供了它的定义:
beforeEachProviders(() => [
provide(UserRegistrationService, { useClass: UserRegistrationServiceMock })
]);
beforeEach(inject([UserRegistrationService], (_userRegistration))
然后在我的实际测试中我可以引用用户注册服务来初始化组件:
it('should create an instance', () => {
let component: BasicRegistrationComponent =
new BasicRegistrationComponent(null, formBuilder, promptWindow, userInfo, translator, userRegistration);
expect(component).toBeTruthy();
});
这里的问题是如何为我的组件提供服务的第二个模拟实现?
最佳答案
您提供第二个模拟类的方式与提供第一个模拟类的方式相同。
将其包含在 beforeEachProviders()
和 beforeEach
中
beforeEachProviders(() => [
provide(UserRegistrationService, { useClass: UserRegistrationServiceMock }),
provide(UserRegistrationServiceSuccess, { useClass: UserRegistrationServiceSuccessMock })
]);
beforeEach(inject([UserRegistrationService, UserRegistrationServiceSuccess], (_userRegistration, _userSuccess))
作为提示,我建议只注入(inject)每个测试所需的内容,而不是将所有依赖项注入(inject)每个测试。 (除非您在该文件中只有一个测试)。保留 beforeEachProviders
,但不要使用 beforeEach
,而是在组件测试中执行此操作:
it("should create an instance", inject([UserRegistrationService, UserRegistrationServiceSuccess], (_userRegistration : UserRegistrationServiceMock, _userSuccess : UserRegistrationServiceSuccessMock) => {
let component: BasicRegistrationComponent =
new BasicRegistrationComponent(null, formBuilder, promptWindow, userInfo, translator, userRegistration);
expect(component).toBeTruthy();
}));
此外,如果您正在使用模拟服务,您应该像上面那样引用它们:
_userRegistration:UserRegistrationServiceMock
。基本上,注入(inject)语句的意思是:当测试正在寻找 UserRegistrationService
时,我将它传递给 UserRegistrationServiceMock
但我称它为 _userRegistration
。如果这没有帮助,请告诉我:)
关于angular - 如何提供不同的模拟服务来测试 Angular 2 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38847738/