【发布时间】:2015-12-26 02:15:38
【问题描述】:
首先:我知道 Angular2 处于 alpha 阶段并且经常更改。
我正在使用 Angular2。有一个具有 http 依赖项的可注入服务,我想使用模拟后端进行测试。该服务在应用程序启动时工作,但我没有运气编写测试并让模拟后端做出响应。任何见解,我在测试设置或实施中是否缺少明显的东西?
服务/core.ts:
import { Injectable } from 'angular2/angular2';
import { Http } from 'angular2/http';
@Injectable()
export class CoreService {
constructor(public http:Http) {}
getStatus() {
return this.http.get('/api/status')
.toRx()
.map(res => res.json());
}
}
服务/core_spec.ts:
import {
AsyncTestCompleter,
TestComponentBuilder,
By,
beforeEach,
ddescribe,
describe,
el,
expect,
iit,
inject,
it,
xit
} from 'angular2/test';
import { MockBackend, MockConnection, BaseRequestOptions, Http, Response } from 'angular2/http';
import { Injector, bind } from 'angular2/angular2';
import { ObservableWrapper } from 'angular2/src/core/facade/async'
import { CoreService } from 'public/services/core'
export function main() {
describe('public/services/core', () => {
let backend: MockBackend;
let response: Response;
let coreService: CoreService;
let injector: Injector;
afterEach(() => backend.verifyNoPendingRequests());
it('should get status', inject([AsyncTestCompleter], (async) => {
injector = Injector.resolveAndCreate([
BaseRequestOptions,
MockBackend,
bind(Http).toFactory((backend, options) => {
return new Http(backend, options)
}, [MockBackend, BaseRequestOptions]),
bind(CoreService).toFactory((http) => {
return new CoreService(http);
}, [Http])
]);
backend = injector.get(MockBackend);
coreService = injector.get(CoreService);
response = new Response('foo');
ObservableWrapper.subscribe<MockConnection>(backend.connections, c => {
expect(c.request.url).toBe('/api/status');
c.mockRespond(response);
});
// attempt #1: fails because res argument is undefined
coreService.getStatus().subscribe(res => {
expect(res).toBe('');
async.done();
});
// attempt #2: fails because emitter.observer is not a function
ObservableWrapper.subscribe(coreService.getStatus(), res => {
expect(res).toBe('');
async.done();
});
}));
});
}
相关: https://github.com/angular/angular/issues/3502 https://github.com/angular/angular/issues/3530
【问题讨论】:
-
你有什么错误吗?它到底在做什么?
-
我将错误包含在内。直接订阅 (coreService.getStatus().subscribe(...)) 会收到错误,res 参数返回为未定义。如果我使用 ObservableWrapper.subscribe(...),它会抛出一个错误,指出emitter.observable 不是一个函数。感谢您的提问。
-
如果将
from 'angular2/test'更改为from 'angular2/test_lib'会发生什么?有用吗? -
当您测试请求 url 时,您不会检查它是否是 GET、POST、DELETE 等。只是 url 字符串。这和我现在正在做的一样。我不知道如何测试请求的类型。在 Angular 1 中,我们有类似 $httpBackend.expectGET('api/status') 的东西,你知道我们如何测试它吗?谢谢
-
第一行不应该是
from 'angular2/core'而不是from 'angular2/angular2'吗?当我尝试执行后者时,我的编译器会抱怨。
标签: http dependency-injection typescript angular