javascript - Angular: Testa HTTP med MockBackend, är async() verkligen nödvändigt?
Jag använder MockBackend för att testa kod som beror på @angular/http.
Alla exempel på nätet använder en asynkron testuppsättning, som här:
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)
})));
});
})));
});
Jag har dock testat det och jag är ganska säker på att MockBackend körs helt synkront:
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');
}));
});
Jag skapade ett fullständigt exempel på plunker här: https://plnkr.co/edit/I3N9zL?p=preview
Något måste ha ändrats sedan de där artiklarna skrevs. Kan någon peka mig till den förändringen? Eller missade jag en viktig fakta?
Svar #1
Du har helt rätt i din antagelse, att MockConnection.mockRespond() sänder synkront. async() behövs inte i detta särskilda test.
Jag är författaren till artikeln du har hänvisat till i din fråga och jag har uppdaterat den därefter.
Tack så mycket för att du påpekade detta!
