替代HTTP Mock策略

使用MockBackend的一个替代方法是创建我们自己的轻模拟。 这里我们创建一个对象,然后告诉TypeScript使用类型断言将其视为Http 。 然后我们为它的get方法创建一个监测器,并返回一个类似于真正的Http服务的observable 。

此方法仍然允许我们检查服务是否已请求正确的URL,并返回预期的数据。

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