因此,在Angular2的RC5版本中,他们弃用了HTTP_PROVIDERS
并引入了HttpModule
。对于我的应用程序代码,这工作正常,但我很难在我的Jasmine测试中进行更改。
以下是我目前在规范中所做的事情,但由于不推荐使用HTTP_PROVIDERS,我现在应该做些什么呢?我需要提供而不是HTTP_PROVIDERS吗?在RC5世界中这样做的正确方法是什么?
beforeEach(() => {
reflectiveInjector = ReflectiveInjector.resolveAndCreate([
HTTP_PROVIDERS,
...
]);
//other code here...
});
it("should....", () => { ... });
答案 0 :(得分:11)
现在弃用的HTTP_PROVIDERS被替换为HttpModule是RC5。
在您的describe块中,添加TestBed.configureTestingModule以及必需的导入和提供程序数组属性,如下所示:
describe("test description", () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [SomeService]
});
});
it("expect something..", () => {
// some expectation here
...
})
})
这就是我使用RC5进行单元服务测试的方法,希望这不会在下一个候选版本和最终版本之间进行更改。如果你像我一样,你可能会对发布候选版本之间的弃用量感到沮丧。我希望事情很快稳定下来!
答案 1 :(得分:2)
从RC5之前的代码更新到RC6时,我遇到了类似的问题。为了扩展Joe W上面的答案,我替换了这段代码:
import { ReflectiveInjector, provide } from '@angular/core';
import { HTTP_PROVIDERS, RequestOptions } from '@angular/http';
export function main() {
describe('My Test', () => {
let myService: MyService;
beforeAll(() => {
let injector = ReflectiveInjector.resolveAndCreate([
HTTP_PROVIDERS,
provide(RequestOptions, { useValue: getRequestOptions() }),
MyService
]);
myService = injector.get(MyService);
});
it('should be instantiated by the injector', () => {
expect(myService).toBeDefined();
});
...
使用这个RC6代码(我猜,它也适用于RC5):
import { TestBed } from '@angular/core/testing';
import { HttpModule, RequestOptions } from '@angular/http';
export function main() {
describe('My Test', () => {
let myService: MyService;
beforeAll(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [
{ provide: RequestOptions, useValue: getRequestOptions() },
MyService
]
});
myService = TestBed.get(MyService);
});
it('should be instantiated by the testbed', () => {
expect(myService).toBeDefined();
});
...