如何为具有依赖于http
的构造函数的以下类编写jasmine测试用例import {Injectable} from 'angular2/core';
import {Http, HTTP_PROVIDERS} from 'angular2/http';
@Injectable()
export class MockUserService {
items:Array<any>;
constructor(http:Http){
http.get('http://127.0.0.1:8080/src/data/names.json')
.subscribe(res => {
this.items = res;
console.log('results found');
})
}
}
我尝试了以下方式,
it('Testing user login', inject([MockUserService,Http], (mockUserService:MockUserService ) => {
let http:Http;
let mockUserService: MockUserService = new MockUserService(http);
expect(1+1).toEqual(2);
});
);
我收到DI错误: DI error Image
答案 0 :(得分:1)
这个测试
https://github.com/angular/angular/blob/master/modules/angular2/test/http/http_spec.ts#L104
使用return new Http(backend, defaultOptions);
,其中backend
是MockBackend
(import {MockBackend, MockConnection} from 'angular2/src/http/backends/mock_backend';
答案 1 :(得分:1)
您可以轻松地将beforeEachProviders用于DI:
beforeEachProviders(() => [
HTTP_PROVIDERS,
MockUserService
]);
describe('MockUser Service', () => {
it('Testing user login',
inject([MockUserService], (service: MockUserService) => {
expect(1 + 1).toEqual(2);
}));
});
我希望这对你有帮助(至少6个月前)。