首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在ngOnInit中测试subscribe方法

在ngOnInit中测试subscribe方法
EN

Stack Overflow用户
提问于 2021-05-04 13:17:28
回答 1查看 60关注 0票数 0

我正在测试我的angular组件中的订阅。我的代码如下。

代码语言:javascript
复制
      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方法中的测试执行)测试用例时,我得到以下错误

代码语言:javascript
复制
Error: Expected undefined to be defined.

在inspect元素中,我得到了如下结果

代码语言:javascript
复制
context.js:255 In Service error :  Response with status: 404 Not Found for URL: http://localhost:9876/undefinedgetList()

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

EN

Stack Overflow用户

回答已采纳

发布于 2021-05-04 14:50:00

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

代码语言:javascript
复制
class MyMockService {
  getList = () => { return of(mockList)};
}

接下来,在spec.ts中提供它。

代码语言:javascript
复制
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();
  }))
});
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67379182

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档