[英]Unit test for method that uses a service
我正在為組件編寫單元測試。 其中一個方法使用服務,它給了我一個cannot read property 'then' of undefined
錯誤的cannot read property 'then' of undefined
。
我已經看到如何在測試中調用服務,但我正在嘗試使用一種方法來調用我的規范文件之外的服務。
規格
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
schemas: [CUSTOM_ELEMENTS_SCHEMA],
imports: [...],
declarations: [MyComponent],
providers: [...],
}).compileComponents();
})
);
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should save', () => {
...
component.myMethod();
});
});
成分
public myMethod() {
...
this.myService.something(this.item).then((resp) => {
// Error comes from here
});
}
}
您可以通過模擬服務方法以多種方式解決此問題:
it('should save', () => {
const service = TestBed.inject(MyService);
spyOn(service , 'something').and.returnValue(Promise.resolve('test'));
component.myMethod();
});
let userServiceStub: Partial<MyService>;
myServiceStub = {
something: () => Promise.resolve('test'),
};
// configureTestingModule
providers: [
{ provide: MyService, useValue: MockService(myServiceStub ) }
]
// configureTestingModule
providers: [
MockProvider(MyService, { something: () => Promise.resolve('test') })
]
還有其他方法,但其中一種應該可以。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.