我有用于测试的设置代码
beforeEach(() => {
loggerServiceSpy = jasmine.createSpyObj('LoggerService', ['log', 'naam']);
TestBed.configureTestingModule({
declarations: [UserslistComponent, BizPipe],
providers: [
{ provide: UserdataService, useClass: MockUserdataService },
{ provide: LoggerService, useValue: loggerServiceSpy }
]
}).compileComponents();
fixture = TestBed.createComponent(UserslistComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
我要执行的操作是注入MockUserdataService
(确实如此)和创建的loggerServiceSpy
的实例。
现在在UserslistComponent
中,注入的LoggerService
类型是“真实” LoggerService
,而不是我的间谍。
通过控制台记录LoggerService的名称已经看到了这一点(我为loggerservice提供了name
属性)。
这是UserslistComponent
的构造函数:
constructor(private userDataService: UserdataService, private logger: LoggerService) {
答案 0 :(得分:1)
如果组件中提供了服务,请尝试覆盖该组件:
beforeEach(() => {
loggerServiceSpy = jasmine.createSpyObj('LoggerService', ['log', 'naam']);
TestBed.configureTestingModule({
declarations: [UserslistComponent, BizPipe],
}).overrideComponent(UserslistComponent, {
set: {
providers: [
{ provide: UserdataService, useClass: MockUserdataService },
{ provide: LoggerService, useValue: loggerServiceSpy }
],
}
}).compileComponents();
fixture = TestBed.createComponent(UserslistComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});