如何对使用服务进行 GET 调用的 Angular 组件进行单元测试

时间:2021-01-10 18:44:35

标签: angular typescript jasmine karma-jasmine

这个问题在这里: How to unit test a component that calls observable service 有一个可接受的答案。但我现在不想测试服务。我在服务器上存储了一些文章。我有一个组件 ArticlesComponent,它使用 ArticlesService 来获取所有这些文章。今天我只想测试 ArticlesComponent。这是代码。

articles.component.ts

import { Component, OnInit } from '@angular/core';
import { ArticleService } from '../article.service';
...


@Component({
  ...
})
export class ArticlesComponent implements OnInit {

  articles = [];
  filteredArticles=[];

  constructor(private _articleService: ArticleService) { 
  }

  ngOnInit() {
    this.getAllArticles();
  }

  getAllArticles() {
    this._articleService.getEvents()
    .subscribe(
      res => {
        this.articles = res,
        this.filteredArticles = res},
      err => console.log(err)
    )
  }
}

ngOnInit 被调用时,它会同时调用 getAllArticles。这是失败的规范文件。

articles.component.spec.ts

import { HttpClientTestingModule } from '@angular/common/http/testing';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
...
import { ArticlesComponent } from './articles.component';

fdescribe('ArticlesComponent', () => {
  let component: ArticlesComponent;
  let fixture: ComponentFixture<ArticlesComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ArticlesComponent],
      imports: [
       ...
        HttpClientTestingModule
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ArticlesComponent);
    component = fixture.debugElement.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  /* THIS CASE IS FAILING*/
  it('should call ngOnInit', () => {
    const fixture = TestBed.createComponent(ArticlesComponent);
    const component = fixture.debugElement.componentInstance;
    let spy_getAllArticles = spyOn(component,"getAllArticles").and.returnValue([]);
    component.ngOnInit();
    expect(component.filteredArticles).toEqual([]);
  })
});

为什么它失败了,抱怨方法不存在:

enter image description here

0 个答案:

没有答案