1

那是代码:

import {
  async,
  inject,
  TestBed
} from '@angular/core/testing';
import {
  Http,
  Response,
  ResponseOptions,
  RequestOptions,
  BaseRequestOptions,
  ConnectionBackend
} from "@angular/http";
import {MockBackend, MockConnection} from "@angular/http/testing";
import {HttpInterceptor, RequestWrapped} from "./http.interceptor.service.ts";

describe("Http interceptor", () => {
  beforeEach(() =>{
    TestBed.configureTestingModule({
      providers: [
        MockBackend,
        BaseRequestOptions,
        {provide: ConnectionBackend, useClass: MockBackend},
        {provide: RequestOptions, useClass: BaseRequestOptions},
        Http
      ],
    });
  });

  it('should get blogs', inject([Http, MockBackend], (http:Http, backend:MockBackend) => {
    let connection:MockConnection;
    backend.connections.subscribe(connection =>
      connection.mockRespond(new Response(new ResponseOptions('awesome')))
    );
    http.request('data.json').subscribe((res) => {
      expect(res.text()).toBe('awesome2');
    });
  }));
});

这个测试应该失败,显然awesome 不等于awesome2,为什么不工作?

4

1 回答 1

1

这是因为该it方法在异步回调之前完成执行。在香草茉莉花中,您将处理异步done

it('', function (done) {
  setTimeout(function () {
    expect(2).toBe(2);
    done();
  }, 1000);
});

done就是 Jasmine 如何知道我们已完成所有异步事件并且测试已完成。

使用 Angular,done我们应该在async. 这会将整个方法包装在一个区域中,在该区域中跟踪所有异步调用。当所有异步调用都完成后,测试就完成了。这与同步测试不同,在同步测试中,一旦方法完成,测试就完成了

import { async } from '@angular/core/testing';                

                    // async wapper
it('should get blogs', async(inject([Http, MockBackend], (http:Http, backend:MockBackend) => {
  let connection:MockConnection;
  backend.connections.subscribe(connection =>
    connection.mockRespond(new Response(new ResponseOptions('awesome')))
  );
  http.request('data.json').subscribe((res) => {
    expect(res.text()).toBe('awesome2');
  });
})));

还有fakeAsync,可以让你控制“滴答声”

it('should get blogs', fakeAsync(inject([Http, MockBackend], (http:Http, backend:MockBackend) => {
  let connection:MockConnection;
  backend.connections.subscribe(connection =>
    connection.mockRespond(new Response(new ResponseOptions('awesome')))
  );
  let text;
  http.request('data.json').subscribe((res) => {
    text = res.text();
  });
  tick();
  expect(res.text()).toBe('awesome2');
})));
于 2016-09-12T11:51:53.603 回答