【问题标题】:Testing subscribe method in ngOnInit在 ngOnInit 中测试订阅方法
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 我需要放哪里 class MyMockService { getList = () => { return of(mockList)}; } 代码?在同一个规范文件本身?你可以给一个stackblitzz吗?
    • 当然。请将您的最小代码放入 stackblitz 中,我可以对其进行编辑并将其发回。
    • 是的,您在测试类声明之前将模拟类放在同一个规范文件中。您也可以将其放在单独的文件中。这取决于你。
    • Drashti 您的大多数建议都有效。我只是在“expect(component.dataSource.length).toBeGreaterThan(0);”上遇到错误行,错误为“预期未定义大于 0。”
    • 能否请您指导我,或者您是否可以在我的上述代码中看到任何错误
    猜你喜欢
    • 2020-02-12
    • 1970-01-01
    • 2019-04-16
    • 2021-06-22
    • 2018-12-27
    • 2019-11-14
    • 2022-07-31
    • 2019-06-15
    • 1970-01-01
    相关资源
    最近更新 更多