ngParty / ng-metadata

Angular 2 decorators and utils for Angular 1.x

Home Page:https://hotell.gitbooks.io/ng-metadata/content/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

service testing documentation hard to understand

david-gang opened this issue · comments

This is the code from the documentation

describe('Hero service test', () => {
  let heroService: HeroService;
  let $httpBackend;

  beforeEach(() => {
    const TestModule: string = bundle(HeroService).name;
    angular.mock.module(TestModule);

    $httpBackend = $injector.get<IHttpBackendService>('$httpBackend');
    heroService = $injector.get<HeroService>(getInjectableName(HeroService));
  });

  afterEach(() => {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  it('should get heroes collection', () => {
    const heroes = [{
      name: 'superman'
    }];
    $httpBackend.expectGET('api/heroes').respond(heroes);
    const result = heroService.getHeroes();

    $httpBackend.flush();

    expect(result).toEqual(heroes);
  });
});

A couple of issues:

  • There are no imports
  • A service cannot be bundled so we have to bundle the module
  • $injector has to be instantiated.

So this leads to a code like here:

import {HeroService} from '<hero service path>';
import {HeroModule} from '<hero module path>';
import {bundle, getInjectableName} from 'ng-metadata/core';
import * as angular from 'angular';

describe('Hero service test', () => {
  let heroService: HeroService;
  let $httpBackend;

  beforeEach(() => {
    const TestModule: string = bundle(HeroModule).name;
   const a = angular as any; // otherwise i get a typescript error. Sure there is a better way
    a.mock.module(TestModule);
   const $injector = angular.injector([TestModule]);

    $httpBackend = $injector.get<IHttpBackendService>('$httpBackend');
    heroService = $injector.get<HeroService>(getInjectableName(HeroService));
  });

  afterEach(() => {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  it('should get heroes collection', () => {
    const heroes = [{
      name: 'superman'
    }];
    $httpBackend.expectGET('api/heroes').respond(heroes);
    const result = heroService.getHeroes();

    $httpBackend.flush();

    expect(result).toEqual(heroes);
  });
});

Please let me know if i miss something