How to unit test an Angular component that is making GET call using a service

拈花ヽ惹草 提交于 2021-01-29 14:58:52

问题


This question here: How to unit test a component that calls observable service has an accepted answer. But I don't want to test the service right now. I've some articles stored on a server. I've a component ArticlesComponent which uses ArticlesService to fetch all those articles. Today I want to test ArticlesComponent only. Here is the code.

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

When ngOnInit gets called then it calls getAllArticles along with it. Here is the spec file which is failing.

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

Why it is failing, complaining that method doesn't exists:

来源:https://stackoverflow.com/questions/65657111/how-to-unit-test-an-angular-component-that-is-making-get-call-using-a-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!