How to test Angular 2 headers sent by a service using the Http module?

When testing an Angular 2 service that makes HTTP GET, POST, PUT, etc. requests, is there a way to check and verify the sent headers?

+4
source share
1 answer

Yes! If you use the Angular2 MockBackend module inside your unit tests, you can subscribe to the connections and check your headers inside. For instance:

var mockBackend = TestBed.get(MockBackend); 
mockBackend.connections.subscribe((connection: MockConnection) => {
      expect(connection.request.headers.get('Content-Type')).toEqu‌al('application/json‌​');         

      let options = new ResponseOptions({
         body: JSON.stringify({ data: 'returned' })
      });
      connection.mockRespond(new Response(options));
 });
+5
source

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


All Articles