我使用MockBackend
来测试依赖于@angular/http
的代码
Web上的所有示例都使用异步测试设置,如下所示:
thoughtram: Testing Services with Http in Angular
describe('getVideos()', () => {
it('should return an Observable<Array<Video>>',
async(inject([VideoService, MockBackend], (videoService, mockBackend) => {
videoService.getVideos().subscribe((videos) => {
expect(videos.length).toBe(4);
expect(videos[0].name).toEqual('Video 0');
expect(videos[1].name).toEqual('Video 1');
expect(videos[2].name).toEqual('Video 2');
expect(videos[3].name).toEqual('Video 3');
expect("THIS TEST IS FALSE POSITIVE").toEqual(false);
});
const mockResponse = {
data: [
{ id: 0, name: 'Video 0' },
{ id: 1, name: 'Video 1' },
{ id: 2, name: 'Video 2' },
{ id: 3, name: 'Video 3' }
]
};
mockBackend.connections.subscribe((connection) => {
connection.mockRespond(new Response(new ResponseOptions({
body: JSON.stringify(mockResponse)
})));
});
})));
});
然而,我试过了,我很确定MockBackend执行完全同步:
describe('getVideos()', () => {
it('should return an Observable<Array<Video>>',
inject([VideoService, MockBackend], (videoService, mockBackend) => {
const mockResponse = {
data: [
{ id: 0, name: 'Video 0' },
{ id: 1, name: 'Video 1' },
{ id: 2, name: 'Video 2' },
{ id: 3, name: 'Video 3' },
]
};
mockBackend.connections.subscribe((connection) => {
connection.mockRespond(new Response(new ResponseOptions({
body: JSON.stringify(mockResponse)
})));
});
let videos;
videoService.getVideos().subscribe(v => videos = v);
// synchronous code!?
expect(videos.length).toBe(4);
expect(videos[0].name).toEqual('Video 0');
expect(videos[1].name).toEqual('Video 1');
expect(videos[2].name).toEqual('Video 2');
expect(videos[3].name).toEqual('Video 3');
}));
});
我在这里创建了一个关于plunker的完整示例: https://plnkr.co/edit/I3N9zL?p=preview
自撰写这些文章以来,必须改变一些东西。 有人能指出我那个突破性的变化吗?或者我错过了一个重要的事实?
答案 0 :(得分:5)
你完全正确的假设,MockConnection.mockRespond()
发出同步。在这个特定的测试中不需要async()
。
我是您在问题中提及的文章的作者,我已相应更新了该文章。
非常感谢您指出这一点!