【发布时间】:2021-05-04 05:17:27
【问题描述】:
我正在测试我的角度组件中的订阅。我的代码如下。
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);
}))
});
我在运行第二个(订阅方法中的测试执行)测试用例时遇到以下错误
Error: Expected undefined to be defined.
在检查元素中我正在关注
context.js:255 In Service error : Response with status: 404 Not Found for URL: http://localhost:9876/undefinedgetList()
如何解决这些错误并让我的测试用例正常工作
【问题讨论】:
标签: angular jasmine karma-jasmine angular8