Angular 2模拟响应不起作用

时间:2016-07-20 15:30:57

标签: testing angular

我有以下Angular 2测试:

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

  }));

});

我想关注的部分是:

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

  }));

当我进行测试时,我得到:

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

认为这可能是一个异步问题,我改变了对此的期望:

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

但我仍然收到同样的失败信息。

我可以做些什么来让模拟响应生效?

2 个答案:

答案 0 :(得分:3)

这是解决方案。我只需要改变

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

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

所以我只需要添加.json()部分即可。

答案 1 :(得分:0)

请看这里的例子: https://angular.io/docs/ts/latest/api/core/testing/async-function.html

并使用它。你试图以同步的方式做所有事情,这是错误的。