在 ngOnInit 中测试订阅方法

Testing subscribe method in ngOnInit

我正在我的 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);
  }))

});

我在 运行 第二个(订阅方法中的测试执行)测试用例

上收到以下错误
Error: Expected undefined to be defined.

并且在 inspect element 中我得到了关注

context.js:255 In Service error :  Response with status: 404 Not Found for URL: http://localhost:9876/undefinedgetList()

如何解决这些错误并使我的测试用例正常工作

不要使用实际服务,而是模拟它。

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();
  }))
});