如何使用MockBackend正确地对Angular2 http服务进行单元测试?

时间:2016-05-11 15:55:57

标签: unit-testing angular jasmine

运行npm test时出现此错误:

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'

我正在使用此angular2种子:https://github.com/mgechev/angular2-seed我根据此博客更改了科学家名单服务以从http获取数据:http://chariotsolutions.com/blog/post/testing-http-services-angular-2-jasmine/

所以我使用ScientistasScientist方法创建了我的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);
          });
      }));
  });
}

这似乎是一个语法错误,但不是一个非常明显的错误,所以任何类型的帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

也许您需要从angular2 / testing模块导入所有测试方法。

像这样:

<httpRuntime targetFramework="4.5.2" maxRequestLength="102400" executionTimeout="6000" />

因为在你的代码中我看到你只是导入&#34; beforeEachProviders&#34;和&#34;注入&#34;。