mfrachet
mfrachet

Reputation: 8922

Angular 2 and unit testing with services

I m trying to unit test an angular 2 service and I m having some troubles.

My class looks like following :

import { Injectable } from '@angular/core';
import {Http} from '@angular/http';

@Injectable()
export class BoardServiceService {

  private http:Http;

  constructor(http:Http) {
    this.http = http;
  }

  /**
   * Load a list of remote boards
   * @return {object} The HTTP observable
   */
  loadBoards(){
    return this.http.get('http://google.com');
  }

}

My test looks like following. I need to test that I get an array of one item for the first test :

import {
  beforeEachProviders,
  it,
  describe,
  expect,
  inject
} from '@angular/core/testing';

import {Http, BaseRequestOptions, Response, ResponseOptions} from '@angular/http';
import {MockBackend} from '@angular/http/testing';
import {provide} from '@angular/core';
import { BoardServiceService } from './board-service.service';

describe('BoardService Service', () => {


  beforeEachProviders(() => [
    BaseRequestOptions,
    MockBackend,
    Response,
    BoardServiceService,
    provide(Http, {
      useFactory: (backend, defaultOptions) => new Http(backend, defaultOptions),
      deps: [MockBackend, BaseRequestOptions]
    })
  ]);

  it('should get me a list of items (array type) on subscribe',
    inject([BoardServiceService, MockBackend], (service: BoardServiceService, MockBackend) => {

      const resultSet = [{}];
      const response = new Response(new ResponseOptions({body:resultSet, status:200}));
      MockBackend.connections.subscribe(connection => connection.mockRespond(response));

      BoardServiceService.loadBoards().subscribe(res => expect(res.length).toEqual(1));
    }));
});

When I try to run my test using angular cli (ng test), I have the following error :

The Broccoli Plugin: [BroccoliTypeScriptCompiler] failed with: Error: Typescript found the following errors:
C:/Project/angular2/kanboard/tmp/broccoli_type_script_compiler-input_base_path-NaWokBRS.tmp/0/src/app/service/boardService/board-service.service.spec.ts (35, 27): Property 'loadBoards' does not exist on type 'typeof BoardServiceService'.

Does anybody knows how to make it work ?

Upvotes: 1

Views: 567

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202176

I think that you should use the following:

service.loadBoards().subscribe(res => expect(res.length).toEqual(1));

instead of

BoardServiceService.loadBoards().subscribe(res => expect(res.length).toEqual(1));

The injected instance not the class itself...

Upvotes: 3

Related Questions