角:测试HTTP与MockBackend,是异步()真正需要的?

我使用MockBackend测试取决于在@angular/http代码。
所有网络上的例子使用异步测试设置,喜欢这里:
thoughtram: Testing Services with Http in Angular角:测试HTTP与MockBackend,是异步()真正需要的?

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

东西必须被改变,因为这些文章写。 有人能指出我到重大更改?还是我错过了一个重要的事实?

回答:

你与你的设想完全正确,那MockConnection.mockRespond()发出同步。在这个特定的测试中不需要async()

我你已经在你的问题中提到的文章的作者,我已经相应地更新它。

非常感谢您指出了这一点!

以上是 角:测试HTTP与MockBackend,是异步()真正需要的? 的全部内容, 来源链接: utcz.com/qa/260887.html

回到顶部