0

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:

enter image description here

Tanzeel
  • 4,174
  • 13
  • 57
  • 110
  • 1
    The mentioned question with an accepted answer at the beginning contains the right approach. It does not contain the testing of the service itself but mocking the service for the component test. A mock object needs to be created for the service and it needs to be provided in the tested component. – Milan Tenk Jan 10 '21 at 19:16
  • @MilanTenk, I'm following this : https://codehandbook.org/how-to-unit-test-angular-component-with-service/ – Tanzeel Jan 10 '21 at 19:24
  • @MilanTenk, but still it should not show "message not found". It is there, we all can see it. Please explain this. – Tanzeel Jan 10 '21 at 19:26
  • Hm.. Yes it is strange that the `getAllArticles()` method is not found. I spotted that there is a global `let component: ArticlesComponent;`, it is assigned in `beforeEach` and in the `it` there is a `const component = fixture.debugElement.componentInstance;` where the `component` variable has the same name as the global one. Could you please try to remove this redundant variable? I think the global one is fine, because in the `beforeEach` it is assigned with the right value. – Milan Tenk Jan 10 '21 at 19:39
  • Is `article.component.ts` or `articles.component.ts`? – Lin Du Jan 11 '21 at 04:12
  • @slideshowp2, it is `articles`. Edited the question also. – Tanzeel Jan 11 '21 at 04:16
  • @Tanzeel: There are few suggestions that I would make but first I would like to address the main issue. Can you confirm that `getAllArticles` is not `private` ? Also , can u try putting `console.log(component.getAllArticles)` in spec file ? See if you are able to access the method. If not `log` the `component` object and see which component does it belong to – Shashank Vivek Jan 11 '21 at 05:40
  • @ShashankVivek, If I remember you've written some articles on Unit testing in angular. Please share that link I would like to go through it again. – Tanzeel Jan 17 '21 at 14:27
  • 1
    @Tanzeel: There you go : https://shashankvivek-7.medium.com/testing-a-component-with-stub-services-and-spies-in-jasmine-1428d4242a49 . – Shashank Vivek Jan 18 '21 at 04:39

0 Answers0