问题
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