ngParty / ng-metadata

Angular 2 decorators and utils for Angular 1.x
https://hotell.gitbooks.io/ng-metadata/content/
MIT License
355 stars 46 forks source link

service testing documentation hard to understand #184

Closed david-gang closed 4 years ago

david-gang commented 7 years ago

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:

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