gpt4 book ai didi

javascript - Angular 2 和服务单元测试

转载 作者:行者123 更新时间:2023-11-30 11:58:52 24 4
gpt4 key购买 nike

我正在尝试对 Angular 2 服务进行单元测试,但遇到了一些麻烦。

我的类(class)如下所示:

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 测试)运行我的测试时,出现以下错误:

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'.

有人知道如何让它工作吗?

最佳答案

我认为您应该使用以下内容:

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

代替

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

注入(inject)的实例不是类本身...

关于javascript - Angular 2 和服务单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37179463/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com