我正在尝试对服务进行单元测试,我嘲笑数据并期待一些结果但是会出错 下面是我的组件ts文件 ts文件
setPrefixSuffixDetails(): void {
this.profileService.getPrefixSuffixDetails()
.subscribe(
data => {
if(data.body.prefixlist.length > 0) {
this.prefixConfig.options = data.body.prefixlist;
}
}
);
}
以下是我的 规格文件
providers: [{provide: ProfileService, useClass: ProfileStub}]
beforeEach(() => {
fixture = TestBed.createComponent(ProfileBeneficiariesViewComponent);
component = fixture.componentInstance;
component.ngOnInit();
profileService = fixture.debugElement.injector.get(ProfileService);
});
let data = {body:['prefixList']}
it('should have a method to get details', () => {
profileService = fixture.debugElement.injector.get(ProfileService);
spyOn(profileService, 'getPrefixSuffixDetails').and.callThrough();
component.ngOnInit();
expect(data.body).toContain([ 'prefixlist' ]);
});
我得到的错误在
之下Error: <spyOn> : could not find an object to spy upon for setPrefixSuffixDetails()
Usage: spyOn(<object>, <methodName>)
class ProfileStub {
getPrefixSuffixDetails = function () {
return Observable.of(data);
}
答案 0 :(得分:0)
请勿在{{1}}中使用this
关键字。您可以直接访问spyOn()
。
profileService
这应解决您的it('should have a method to get details', () => {
let response: {"body":{"prefixlist":["DEACON","DR","MISS","MR","MRS","MS","PASTOR","REV"],"suffixlist":["I","II","III","IV","Jr","Sr"]}};
spyOn(profileService, 'setPrefixSuffixDetails').and.callThrough().and.
returnValue(Observable.of(response));
fixture.detectChanges();
expect(response.body).toContain('prefixList');
});
错误。
答案 1 :(得分:0)
使用inject
中的@angular/core/testing
注入依赖项
您的规格文件应该是这样的
describe('ProfileBeneficiariesViewComponent', () => {
let component: ProfileBeneficiariesViewComponent;
let fixture: ComponentFixture< ProfileBeneficiariesViewComponent >;
let profileService;
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
{provide: ProfileService, useClass: ProfileStub}
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ProfileBeneficiariesViewComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
beforeEach(inject([ProfileService], s => {
profileService = s;
}));
it('Do Your test', () => {
expect(component).toBeTruthy();
});
});