Жасмин тестирует ошибку StaticInjector для тестирования компонентов - PullRequest
0 голосов
/ 07 сентября 2018

У меня есть мой угловой компонент, который вызывает сервис и отображает данные в интерфейсе пользователя. При написании тестовых случаев я внедряю фиктивную службу для моего компонента и запускаю свой тестовый пример.

Служба имеет зависимость 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.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...