我有一个独立的班需要测试角度。我不知道如何才能为它注入模拟服务。
我尝试使用TestBed来依赖注入服务。但这不起作用。
// user-setting.ts, class I want to test
constructor(private config: UserSettingDefault, private userSettingsService: UserSettingsService) { }
// user-setting.spec.ts, I try to use TestBed to inject, but failed
class UserSettingsServiceMock {
}
fdescribe('UserSetting', () => {
let userSettingsService: UserSettingsServiceMock
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{ provide: UserSettingsService, useClass: UserSettingsServiceMock },
],
});
userSettingsService = TestBed.get(UserSettingsService);
});
it('should create an instance', () => {
const config = { app: 'user', type: 'search', id: 'embeded-link' };
const userSetting = new UserSetting(config, userSettingsService);
expect(userSetting).toBeTruthy();
});
});
我希望我可以为UserSetting创建一个新实例。但是抛出一些错误:
ERROR in src/app/core/user/user-settings/user-setting.spec.ts(25,49): error TS2345: Argument of type 'UserSettingsServiceMock' is not assignable to parameter of type 'UserSettingsService'.
Property 'language' is missing in type 'UserSettingsServiceMock'.
答案 0 :(得分:0)
因此,如果要在组件中模拟服务,则必须提供该服务的虚拟框架(即,您需要在该模拟注入依赖项中编写模拟方法和变量,这些都是组件正在使用的)。
您将收到错误消息,因为必须在组件中使用userSettingsService.language
。因此,您还需要模拟该值。
class UserSettingsServiceMock {
language = {};
}