mercredi 20 juillet 2016

Angular 2 mock response not working

I have the following Angular 2 test:

/* tslint:disable:no-unused-variable */

import { provide  } from '@angular/core';
import { MockBackend  } from '@angular/http/testing';

import {
  Http,
  HTTP_PROVIDERS,
  Response,
  ResponseOptions,
  BaseRequestOptions,
  ConnectionBackend,
  XHRBackend

} from '@angular/http';

import {
  beforeEach, beforeEachProviders,
  describe, xdescribe,
  expect, it, xit,
  async, inject

} from '@angular/core/testing';

import { BookService  } from './book.service';

describe('Book Service', () => {
  beforeEachProviders(() => [
    BookService,
    HTTP_PROVIDERS,
    MockBackend,
    BaseRequestOptions,
    { provide: XHRBackend, useExiting: MockBackend  },
    provide(Http, {
        useFactory: function (backend:ConnectionBackend, defaultOptions:BaseRequestOptions) {
        return new Http(backend, defaultOptions);
      },
      deps: [MockBackend, BaseRequestOptions]
    })
  ]);

  it('should assign a list of books', inject([BookService, MockBackend, Http], (service, backend, http) => {
     var response;

     backend.connections.subscribe(c => {
       expect(c.request.url).toEqual('/api/books.json');
       c.mockRespond(new Response(new ResponseOptions({body: {message: 'thank you'}})));

       });

     http.get('/api/books.json').subscribe(data => response = data);

     expect(response).toEqual({ message: 'thank you'  });

  }));

});

The part I want to focus on is this:

  it('should assign a list of books', inject([BookService, MockBackend, Http], (service, backend, http) => {
     var response;

     backend.connections.subscribe(c => {
       expect(c.request.url).toEqual('/api/books.json');
       c.mockRespond(new Response(new ResponseOptions({body: {message: 'thank you'}})));

       });

     http.get('/api/books.json').subscribe(data => response = data);

     expect(response).toEqual({ message: 'thank you'  });

  }));

When I run the test, I get:

Expected Response with status: null null for URL: null to equal Object({ message: 'thank you' }).

Thinking it's maybe an async issue, I changed my expectation to this:

http.get('/api/books.json').subscribe(data => {
   expect(data).toEqual({ message: 'thank you'  });
});

But I'm still getting the same failure message.

What can I do to get the mock response to take effect?

Aucun commentaire:

Enregistrer un commentaire