2016-05-11 2 views
2

При запуске npm test я получаю эту ошибку:Как правильно выполнить тестирование услуги Angular2 http с помощью MockBackend?

src/client/app/shared/services/scientist.service.spec.ts(20,7): error TS2345: Argument of type 'Function' is not assignable to parameter of type '(done:() => void) => void'. 
    Type 'Function' provides no match for the signature '(done:() => void): void' 

I'am использованием этого angular2 семян: https://github.com/mgechev/angular2-seed и я изменил имя ученого-лист услуги, чтобы получить данные с HTTP-, основываясь на этом блоге: http://chariotsolutions.com/blog/post/testing-http-services-angular-2-jasmine/.

Итак, я создал свой класс Scientist с помощью методов asScientist и asScientists, которые создают экземпляры из json.

scientist.service.ts:

import {Injectable} from 'angular2/core'; 
import {Http, Response} from 'angular2/http'; 
import {Observable} from 'rxjs/Observable'; 

import {Scientist} from './scientist'; 

@Injectable() 
export class ScientistService { 
    private url = 'http://path/to/scientists/'; 

    constructor(private http:Http) { 
    } 

    get():Observable<Scientist[]> { 
    return this.http.get(this.url) 
     .map((res:Response) => { 
     return Scientist.asScientists(res.json()); 
     }); 
    } 
} 

scientist.service.spec.ts:

import {provide} from 'angular2/core'; 
import {beforeEachProviders, inject} from 'angular2/testing'; 
import {XHRBackend, ResponseOptions, Response} from 'angular2/http'; 
import {MockBackend, MockConnection} from 'angular2/src/http/backends/mock_backend'; 

import {Scientist} from './scientist'; 
import {ScientistService} from './scientist.service.ts'; 

export function main() { 
    describe('Scientist Service',() => { 
    beforeEachProviders(() => { 
     return [HTTP_PROVIDERS, provide(XHRBackend, {useClass: MockBackend}), ScientistService]; 
    }); 

    it('should get the list of scientists', 
     // ##### Line below causes the error ##### 
     inject([XHRBackend, ScientistService], (mockBackend:MockBackend, scientistService:ScientistService) => { 
     mockBackend.connections.subscribe(
      (connection:MockConnection) => { 
      // Haven't changed these yet since I want to make the test pass first 
      connection.mockRespond(new Response(
       new ResponseOptions({ 
        body: [ 
        { 
         id: 26, 
         contentRendered: '<p><b>Hi there</b></p>', 
         contentMarkdown: '*Hi there*' 
        }] 
       } 
      ))); 
      }); 
     scientistService.get().subscribe((scientists:Scientist[]) => { 
      expect(scientists.length).toBe(1); 
      //expect(scientists[0].id).toBe(26); 
      //expect(data[0].contentMarkdown).toBe('*Hi there*'); 
      }, 
      (error:any) => { 
      // we can call a failure case here... 
      fail(error); 
      }); 
     })); 
    }); 
} 

Это, кажется, ошибка синтаксиса, но не очень очевидный, поэтому для любого типа помощь будет оценена!

+0

Какова синтаксическая ошибка? – theUtherSide

+0

В верхней части описания вопроса: 'Тип 'Функция' не дает соответствия для подписи '(done:() => void): void'' at' scientist.service.spec.ts (20,7) ' – fips

ответ

1

Возможно, вам нужно импортировать все методы испытаний из модуля углового2/тестирования.

Как это:

import {it, beforeEachProviders, describe, expect, beforeEach, inject, injectAsync} from 'angular2/testing'; 

Потому что в вашем коде, я видел, как вы просто импортировать "beforeEachProviders" и "впрыснуть".

+0

только обновление для последней версии Angular import {async, описать, это, ожидать, впрыскивать, beforeEach, beforeEachProviders} из '@ angular/core/testing'; –