Angular тестовый сбой при выполнении http-вызова - PullRequest
0 голосов
/ 21 февраля 2020

Это мой файл dashboard.component.ts:

import { Post } from "./../models/post";
import { Component, OnInit } from "@angular/core";

@Component({
  selector: "app-dashboard",
  templateUrl: "./dashboard.component.html",
  styleUrls: ["./dashboard.component.css"]
})
export class DashboardComponent implements OnInit {
  constructor() {}

  title: string = "Hello World!";
  posts: Post[] = [];

  addNumber(a: number, b: number) {
    return a + b;
  }

  ngOnInit() {
  }
}

Это мой файл dashboard.component.spe c .ts:

import { async, ComponentFixture, TestBed } from "@angular/core/testing";

import { DashboardComponent } from "./dashboard.component";

describe("DashboardComponent", () => {
  let component: DashboardComponent;
  let fixture: ComponentFixture<DashboardComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [DashboardComponent]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(DashboardComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it("should add two numbers", () => {
    expect(component.addNumber(1, 1)).toBe(2);
  });

  it("title should contain the word Hello", () => {
    expect(component.title).toContain("Hello");
  });
});

Все в порядке, оба теста являются успешными. Но когда я хочу добавить http-вызов с моей службой, например так:

dashboard.component.ts файл после добавления http-вызова:

import { Post } from "./../models/post";
import { PostService } from "./../services/posts-api.service";
import { Component, OnInit } from "@angular/core";

@Component({
  selector: "app-dashboard",
  templateUrl: "./dashboard.component.html",
  styleUrls: ["./dashboard.component.css"]
})
export class DashboardComponent implements OnInit {
  constructor(private postService: PostService) {}

  title: string = "Hello World!";
  posts: Post[] = [];

  addNumber(a: number, b: number) {
    return a + b;
  }

  ngOnInit() {
    this.postService.getPosts().subscribe(posts => {
      this.posts = posts;
    });
  }
}

http-вызов успешен, но теперь тест не удалось, почему? файл spe c без изменений:

NullInjectorError: StaticInjectorError (DynamicTestModule) [HttpClient]: StaticInjectorError (Платформа: ядро) [HttpClient]: NullInjectorError: Нет поставщика для HttpClient!

вы.

1 Ответ

0 голосов
/ 21 февраля 2020

Вам нужно добавить HttpClientTestingModule в ваш файл spe c, потому что вы внедряете PostService с помощью самого HttpCient:

import {HttpClientTestingModule} from "@angular/common/http/testing";

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [DashboardComponent],
      imports: [HttpClientTestingModule]
    }).compileComponents();
  }));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...