Alternative HTTP Mocking Strategy

An alternative to using MockBackend is to create our own light mocks. Here we create an object and then tell TypeScript to treat it as Http using type assertion. We then create a spy for its get method and return an observable similar to what the real Http service would do.

This method still allows us to check to see that the service has requested the right URL, and that it returns that expected data.

wikisearch.spec.ts

  1. import {
  2. fakeAsync,
  3. inject,
  4. TestBed
  5. } from '@angular/core/testing';
  6. import {
  7. HttpModule,
  8. Http,
  9. ResponseOptions,
  10. Response
  11. } from '@angular/http';
  12. import { Observable } from 'rxjs/Observable';
  13. import 'rxjs/add/observable/of';
  14. import {SearchWiki} from './wikisearch.service';
  15. const mockResponse = {
  16. "batchcomplete": "",
  17. "continue": {
  18. "sroffset": 10,
  19. "continue": "-||"
  20. },
  21. "query": {
  22. "searchinfo": {
  23. "totalhits": 36853
  24. },
  25. "search": [{
  26. "ns": 0,
  27. "title": "Stuff",
  28. "snippet": "<span></span>",
  29. "size": 1906,
  30. "wordcount": 204,
  31. "timestamp": "2016-06-10T17:25:36Z"
  32. }]
  33. }
  34. };
  35. describe('Wikipedia search service', () => {
  36. let mockHttp: Http;
  37. beforeEach(() => {
  38. mockHttp = { get: null } as Http;
  39. spyOn(mockHttp, 'get').and.returnValue(Observable.of({
  40. json: () => mockResponse
  41. }));
  42. TestBed.configureTestingModule({
  43. imports: [HttpModule],
  44. providers: [
  45. {
  46. provide: Http,
  47. useValue: mockHttp
  48. },
  49. SearchWiki
  50. ]
  51. });
  52. });
  53. it('should get search results', fakeAsync(
  54. inject([SearchWiki], searchWiki => {
  55. const expectedUrl = 'https://en.wikipedia.org/w/api.php?' +
  56. 'action=query&list=search&srsearch=Angular';
  57. searchWiki.search('Angular')
  58. .subscribe(res => {
  59. expect(mockHttp.get).toHaveBeenCalledWith(expectedUrl);
  60. expect(res).toEqual(mockResponse);
  61. });
  62. })
  63. ));
  64. });

View Example

原文: https://angular-2-training-book.rangle.io/handout/testing/services/alt-http-mocking.html