我有我的Angular组件,该组件调用服务并在UI上显示数据。在编写测试用例时,我正在向组件注入模拟服务并运行测试用例。
该服务具有HttpClient
的相关性,但是我不想向我的模拟服务注入HttpClient
。但我收到以下错误:
Error: StaticInjectorError(DynamicTestModule)[UserService -> HttpClient]:
StaticInjectorError(Platform: core)[UserService -> HttpClient]:
NullInjectorError: No provider for HttpClient!
这是我示例中的代码段
服务:
import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import {User} from './user';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private httpClient: HttpClient) { }
getAllUsers():Observable<HttpResponse<User>>{
return this.httpClient.get<User>('https://jsonplaceholder.typicode.com/users',{observe:'response'});
}
}
组件:
import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'Welcome to angular-testing!';
users;
constructor(private userService:UserService){this.userService = userService;}
ngOnInit(){
this.userService.getAllUsers();
}
}
app.component.spec.ts
文件的规范文件
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { of } from 'rxjs';
import { UserService } from './user.service';
import { HttpClientModule } from '@angular/common/http';
const userServiceStub = {
getAllUsers() {
console.log('came inside the stub');
const users = [
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz"
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna@melissa.tv"
}
];
return of( users );
}
};
describe('AppComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent,
],
imports:[
HttpClientModule
],
providers: [{provide: UserService, useValue: userServiceStub}]
}).compileComponents();
});
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it(`should have as title 'angular-testing'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('Welcome to angular-testing!');
}));
it('should render title in a h1 tag', async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to angular-testing!');
}));
});
据我所知,如果我模拟服务,则可以提供自己的实现,而不必使用HttpClient
。我要去哪里错了。我正在使用Angular 6版本。