这就是代码:
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');
});
}));
});
这个测试应该失败,显然真棒不等于真棒2,为什么不起作用?
答案 0 :(得分:1)
这是因为it
方法在异步回调之前完成执行。在vanilla Jasmine中,您将处理与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');
})));