我使用angular-cli(最新版本1.0.0-beta.25.5)创建了一个应用程序并添加了一个简单的服务:
import { Injectable } from '@angular/core';
import {Headers, Http} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {Todo} from './todo';
@Injectable()
export class TodoService {
public todoUrl = 'http://localhost:4200/app/todos'; // URL to web api
constructor(public http: Http) {
}
getTodos(): Promise<Todo[]> {
return this.http.get(this.todoUrl)
.toPromise()
.then(response => response.json().data as Todo[])
.catch(this.handleError);
}
handleError(error: any): Promise<any> {
return Promise.reject(error.message || error);
}
}
进行测试:
import {TestBed, inject} from '@angular/core/testing';
import { TodoService } from './todo.service';
import {Todo} from './todo';
import {BaseRequestOptions, Http} from '@angular/http';
import {MockBackendService} from './mock-backend.service';
import {MockBackend} from '@angular/http/testing';
describe('TodoService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
MockBackend,
BaseRequestOptions,
{
provide: Http,
deps: [MockBackend, BaseRequestOptions],
useFactory: (backend: MockBackend, options: BaseRequestOptions) => {
new MockBackendService().SetUpTodoBackend(backend);
return new Http(backend, options);
}
},
TodoService
]
});
});
it('should return array of todos', inject([TodoService], (service: TodoService) => {
service.getTodos().then((todos: Todo[]) => {
console.log(todos.length);
expect(todos.length).toEqual(100);
expect(todos[0].id).toEqual(11);
console.log('Finished.');
});
}));
});
在MockBackendService中,我返回一个包含10个Todos的数组,因此测试应该失败,因为它期望数组包含100个todos。当我运行测试时,我得到以下结果:
LOG: 'mockConnection url:: http://localhost:4200/app/todos'
LOG: 10
LOG: 'Finished.'
Executed 1 of 1 SUCCESS (0.139 secs / 0.126 secs)
因此它记录该数组包含10个结果但仍然通过测试。当我再添加2个&#34;测试&#34;:
it('should pass', () => {});
it('should also pass', () => {});
最后一次测试失败并显示第一次测试中的正确消息:
TodoService should also pass FAILED
Expected 10 to equal 100.
@webpack:///src/app/todo.service.spec.ts:32:6 <- src/test.ts:70258:13 [ProxyZone]
ProxyZoneSpec</ProxyZoneSpec.prototype.onInvoke@webpack:///~/zone.js/dist/proxy.js:79:0 <- src/test.ts:54312:20 [ProxyZone]
Zone$1</Zone</Zone.prototype.run@webpack:///~/zone.js/dist/zone.js:113:0 <- src/test.ts:74539:24 [ProxyZone => ProxyZone]
scheduleResolveOrReject/<@webpack:///~/zone.js/dist/zone.js:535:0 <- src/test.ts:74961:52 [ProxyZone]
ProxyZoneSpec</ProxyZoneSpec.prototype.onInvokeTask@webpack:///~/zone.js/dist/proxy.js:103:0 <- src/test.ts:54336:20 [ProxyZone]
Zone$1</ZoneDelegate</ZoneDelegate.prototype.invokeTask@webpack:///~/zone.js/dist/zone.js:274:0 <- src/test.ts:74700:21 [ProxyZone]
Zone$1</Zone</Zone.prototype.runTask@webpack:///~/zone.js/dist/zone.js:151:0 <- src/test.ts:74577:28 [<root> => ProxyZone]
drainMicroTaskQueue@webpack:///~/zone.js/dist/zone.js:433:0 <- src/test.ts:74859:25 [<root>]
Executed 3 of 3 (1 FAILED) (0.344 secs / 0.133 secs)
我在这里做错了什么才能得到这么奇怪的行为?我可以使用新生成的应用程序重新创建该行为,因此它似乎位于我的代码或我使用的库中......