Angular: Testing HTTP with MockBackend, is async () really required?

I use MockBackend to check for code that depends on @angular/http .
All examples on the Internet use asynchronous test setup, for example:
mindram: 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) }))); }); }))); }); 

However, I have tried this and I am sure that the MockBackend runs completely synchronously:

 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'); })); }); 

I created a complete plunker example here: https://plnkr.co/edit/I3N9zL?p=preview

enter image description here

Something must have changed since these articles were written. Can someone point me to this violation? Or did I miss an important fact?

+5
source share
1 answer

You are absolutely correct with your assumption that MockConnection.mockRespond() emits synchronous. async() not required in this particular test.

I am the author of the article that you mentioned in your question, and I updated it accordingly.

Thank you so much for pointing this out!

+5
source

Source: https://habr.com/ru/post/1261673/


All Articles