Joh*_*ppe 5 javascript typescript angular2-testing angular
我正在MockBackend测试依赖的代码@angular/http.
Web上的所有示例都使用异步测试设置,如下所示:
thoughtram:在Angular中使用Http测试服务
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)
})));
});
})));
});
Run Code Online (Sandbox Code Playgroud)
但是,我试过了,我很确定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');
}));
});
Run Code Online (Sandbox Code Playgroud)
我在这里创建了一个关于plunker的完整示例:https://plnkr.co/edit/I3N9zL ? p = preview
自撰写这些文章以来,一定有些变化.有人能指出我那个突破性的变化吗?还是我错过了一个重要的事实?
你的假设完全正确,它MockConnection.mockRespond()会同步发出.async()在这个特定的测试中不需要.
我是您在问题中提到的文章的作者,我已相应地更新了它.
非常感谢您指出这一点!
| 归档时间: |
|
| 查看次数: |
741 次 |
| 最近记录: |