我正在尝试对angular 2服务进行单元测试,但遇到了一些问题。
我的课看起来如下:
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');
}
}
我的测试如下。我需要测试第一次测试是否得到一个项目的数组:
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));
}));
});
当我尝试使用angular cli(ng test)运行测试时,我会出现以下错误:
Broccoli插件[BroccoliTypeScriptCompiler]失败,返回:错误:Typescript发现以下错误:
C:/项目/angular2/kanboard/tmp/broccoli_type_script_compiler-input_base_path-NaWokBRS.tmp/0/src/app/service/boardService/board-service.spec.ts(35,27):类型"typeof"上不存在属性"loadBoards"BoardServiceService。
有人知道如何让它发挥作用吗?
我认为您应该使用以下内容:
service.loadBoards().subscribe(res => expect(res.length).toEqual(1));
而不是
BoardServiceService.loadBoards().subscribe(res => expect(res.length).toEqual(1));
注入的实例而不是类本身。。。