我正在测试我的angular组件中的订阅。我的代码如下。
MyComponenet.ts
ngOnInit() {
getMyList();
}
getMyList() {
this.myService.getList().subscribe(resp => {
if (resp.length > 0) {
this.dataSource = new MatTableDataSource();
}
}});
MyComponent.spec.ts -
const data= [ {
"id": "1",
"name": "name 1",
},
{
"id": "2",
"name": "name2",
}
]
fdescribe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
let myService: MyService
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MyComponent],
imports: [my imports...],
providers: [MyService]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
myService= TestBed.get(MyService)
fixture.detectChanges();
});
it('testing subscribe method calling', fakeAsync(() => {
let listSpy = spyOn(myService, 'getList').and.returnValue(of(mockList))
let subSpy = spyOn(myService.getList(), 'subscribe');
component.ngOnInit();
tick();
expect(listSpy ).toHaveBeenCalledBefore(subSpy);
expect(subSpy).toHaveBeenCalled();
}))
it('test execution within subscribe method ', fakeAsync(() => {
component.ngOnInit();
expect(component.dataSource).toBeDefined();
expect(component.dataSource.length).toBeGreaterThan(0);
}))
});在运行second( subscribe方法中的测试执行)测试用例时,我得到以下错误
Error: Expected undefined to be defined.在inspect元素中,我得到了如下结果
context.js:255 In Service error : Response with status: 404 Not Found for URL: http://localhost:9876/undefinedgetList()如何解决这些错误并使我的测试用例正常工作?
发布于 2021-05-04 14:50:00
模拟它,而不是使用实际的服务。
class MyMockService {
getList = () => { return of(mockList)};
}接下来,在spec.ts中提供它。
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ your declarations...],
imports: [your imports...],
// provide the component-under-test and dependent service
providers: [
...
{ provide: MyService, useClass: MyMockService }
]
});
});
it('test execution within subscribe method ', fakeAsync(() => {
component.ngOnInit();
expect(component.dataSource).toBeDefined();
expect(component.datasource).not.toBeNull();
}))
});https://stackoverflow.com/questions/67379182
复制相似问题