单位测试角度2 http get / observable

时间:2017-12-04 06:11:40

标签: angular unit-testing jasmine angular-cli angular2-http

我正在尝试编写一个单元测试来测试我从调用我的Api验证的json验证模拟对象,但我总是最终得到从WebApi返回的数据是未定义的。我相信这是因为Api返回一个Observable,并且在测试运行时尚未解决。

在过去的几天里,我用谷歌搜索了我能想到的与此相关的所有内容,但完全没有解决方案。这是我的第一个Angular2项目没有帮助。这里有人可以指出我正确的方向吗?

这是我从WebApi获得的Json

{
"Categories": [
    "categoryA",
    "categoryB"        
]
}

这是我的断言。 ' retrivedData'无论我尝试什么,总是不确定

return siteService.getCategories({ category: 'all' }).subscribe((retrivedData) => {
    expect(retrivedData.length).toBe(2);
    expect(retrivedData[0]).toEqual(mockArrayOfCategories[0]);
    expect(retrivedData[1]).toEqual(mockArrayOfCategories[1]);
  });

这是我的unittest(getCategories.spec.ts)

import { TestBed, fakeAsync, inject, tick } from '@angular/core/testing';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { BaseRequestOptions, Http, Response, ResponseOptions } from '@angular/http';

import { SiteService } from './siteService.service';
import { HierarchyItem } from '../../models/HierarchyItem';
import { hasLifecycleHook } from '@angular/compiler/src/lifecycle_reflector';
import { Category } from '../../models/Category';

describe('SiteService', () => {
  let siteService: SiteService;
  let mockBackend: MockBackend;

beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [
      SiteService,
      MockBackend,
      BaseRequestOptions,
    {
      provide: Http,
      useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
        return new Http(backend, defaultOptions);
      },
      deps: [MockBackend, BaseRequestOptions]
    }
  ]
});
});

beforeEach(inject([
  SiteService,
  MockBackend
], (_siteService: SiteService,
_mockBackend: MockBackend) => {

  siteService = _siteService;
  mockBackend = _mockBackend;
}));

afterEach(() => {
  mockBackend.verifyNoPendingRequests();
});

describe('getCategories', () => {
  it('should return an Observable<Array<Category>> containing 2 categores; A and B', fakeAsync(() => {
  // Arrange
  const mockArrayOfCategories = new Array<Category>();
  let mockCategory = new Category();
  mockCategory.name = 'categoryA';
  mockArrayOfCategories.push(mockCategory);

  mockCategory = new Category();
  mockCategory.name = 'categoryB';
  mockArrayOfCategories.push(mockCategory);

  const response = new Response(new ResponseOptions({
    body: { value: mockArrayOfCategories }
  }));
  mockBackend.connections.subscribe((connection: MockConnection) => connection.mockRespond(response));

  // Act
  const categorySubscription = siteService.getCategories({ category: 'all' });
  tick();

  // Assert
  return categorySubscription.subscribe((retrivedData) => {
    expect(retrivedData.length).toBe(2);
    expect(retrivedData[0]).toEqual(mockArrayOfCategories[0]);
    expect(retrivedData[1]).toEqual(mockArrayOfCategories[1]);
  });

}));
});
});

和正在测试的方法

getCategories(context: SiteContext): Observable<Array<Category>> {
    return this.http.get(routes.getCategories(context), { cache: true })
      .map((res: Response) => <Array<Category>>res.json().Categories)
      .do(data => console.log(data))
      .catch(this.handleError);
  }

0 个答案:

没有答案