insideEach中的mockRespond方法在XHR之后调用后端内部测试

时间:2016-11-25 14:51:48

标签: unit-testing angular jasmine

我正在尝试使用Angular2中的MockBackend编写Jasmine测试。

以下是我编写的用于测试与后端通信的服务的代码:

import { inject, TestBed } from '@angular/core/testing';

import {VehicleCategoryService} from './VehicleCategoryService';

import { BaseRequestOptions, Response, ResponseOptions, Http } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';
import {HttpService} from "../../api/HttpService";
import {ApplicationService} from "../../api/ApplicationService";

describe('VehicleCategoryService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [VehicleCategoryService,BaseRequestOptions, MockBackend, ApplicationService, {
        provide: HttpService,
        useFactory: (backend, options, applicationService) => {
          return new HttpService(backend, options, applicationService);
        },
        deps: [MockBackend, BaseRequestOptions, ApplicationService],
      }],
    });
  });

  beforeEach(inject([MockBackend], (backend: MockBackend) => {
    const baseResponse = new Response(new ResponseOptions({ body: '{"Name":"MiniVan"}' }));
    backend.connections.subscribe((c: MockConnection) => c.mockRespond(baseResponse));
  }));

  it('should be defined', inject([VehicleCategoryService], (vehicleCategoryService: VehicleCategoryService) => {
    expect(vehicleCategoryService).toBeDefined();
  }));

  it('should return response when querying vehicleCategories', inject([VehicleCategoryService], (vehicleCategoryService: VehicleCategoryService) => {
    vehicleCategoryService.query().subscribe((res: Response) => {
      expect(res['Name']).toBe('MiniVan');
    });
  }));
});
http://stackoverflow.com/questions/ask#

这里的HttpService是一个从内置的Http Angular2服务扩展而来的服务。 query()方法返回Observable作为通常的Http做。 调试问题表明订阅中的mockRespond()方法比实际调用后端调用更晚,这就是我收到未定义响应的原因。我该如何解决这个问题?

0 个答案:

没有答案