使用构造函数实例化服务 http: Http in Angular 2

Instantiate Service with constructor http: Http in Angular 2

我这里有这项服务 class:

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import {ReflectiveInjector} from '@angular/core';
import { Observable } from 'rxjs/Rx';

import { Nota } from './nota.model';
import { HttpUtilService } from '../services/http-util.service';

import moment = require('moment');

const TIPOS_DOC : any[] = [
  {id: 1, nome: "Sem Referência"},
  ...

@Injectable()
export class NotaService {

    constructor(private http: Http, private httpUtil: HttpUtilService) { }

// methods ...
}

我想在我的规范文件中实例化这个服务,这样我就可以调用这些方法并进行测试。但是当我实例化服务时,我不知道如何正确使用 http: Http。这是我的测试文件:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By }              from '@angular/platform-browser';
import { DebugElement }    from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';

import { HttpUtilService } from '../../services/http-util.service';

import { NotaService } from '../nota.service';

describe ('Tests for the service Nota response', () => {

  beforeEach(() => {
      let http_service  = new HttpUtilService();
      let http: Http;
      this.nota_service = new NotaService(http, http_service);
  });
  it ('testes ...')
  ...

});

我没有收到任何语法错误,但这个测试文件不起作用。

如果您检查 beforeEach 中的代码,您基本上是在定义 Http,但根本没有实例化它。您的 NotaService 将收到 NULL 参考。参见:

  let http: Http;
  this.nota_service = new NotaService(http, http_service);

常见的做法是提供一些假的Http服务(Mock)并将其注入到你的服务中。你需要告诉 Angular 2: "if someone wants Http, give him Mocked version".

在你的测试中使用这样的东西:

import { addProviders, inject } from '@angular/core/testing';
import { Http, BaseRequestOptions } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { NotaService} from '../nota.service';

...

beforeEach(() => {
  addProviders([
    MockBackend,
    BaseRequestOptions,
    {
      provide: Http,
      useFactory: (backendInstance: MockBackend, defaultOptions: BaseRequestOptions) => {
        return new Http(backendInstance, defaultOptions);
      },
      deps: [MockBackend, BaseRequestOptions]
    },
    NotaService
  ]);
});

查看这篇文章以获得详细解释Testing Angular 2 HTTP Services with Jasmine 并查找 Introducing the HTTP Service

部分

这是我做测试的正确方式。

首先,在 Angular 2 中,您永远不应尝试在前端(视图)测试中实例化服务。始终使用模拟。它们真的很容易创建和使用。

这里是模拟文件的例子

// import the model you want to test and their dependencies
import { Post } from "../app/post/post.model";
import { UserTestMock } from "./mocks/user.test";

// create a normal class that will be the mock of your model
export class PostTestMock {

  static getMock(id: number): Post {
    const post = new Post(
      id,
      "Title of my post",
      "The body of my post ... end of body.",
      UserTestMock.getMock(1)
    );

    return post;
  }
}

比起你的测试文件,你只需要使用(导入它)你的模拟

  it("Should test something", async(() => {
    let post = PostTestMock.getMock(1);
    // just an example of some function that you want to call
    yourTest.send(post)
  }));