我进行http调用时出现角度测试失败

时间:2020-02-21 14:08:13

标签: angular karma-jasmine

这是我的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.spec.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调用时,如下所示:

添加http调用后的

dashboard.component.ts文件:

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调用成功,但是现在测试失败,为什么?规格文件没有更改:

NullInjectorError:StaticInjectorError(DynamicTestModule)[HttpClient]: StaticInjectorError(平台:核心)[HttpClient]: NullInjectorError:HttpClient没有提供程序!

谢谢。

1 个答案:

答案 0 :(得分:0)

因为您是使用HttpCient本身注入PostService的,所以还需要向规范文件中添加HttpClientTestingModule

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

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