我想使用模拟服务运行我的组件,而不是实际的服务。 我在beforeEachProviders中提供了模拟服务(MockMyService),但它仍在调用实际的服务。
describe('List view component', () => {
beforeEachProviders(() => {
return [
ROUTER_PROVIDERS,
HTTP_PROVIDERS,
provide(RouteParams, { useValue: new RouteParams({ query: 'test' }) }),
provide(MyService, { useClass: MockMyService }),
MyComponent,
provide(APP_BASE_HREF, { useValue: '/' }),
provide(ROUTER_PRIMARY_COMPONENT, { useValue: AppComponent }),
provide(ApplicationRef, { useClass: MockApplicationRef })
];
});
it('1: component value check',
async(inject([TestComponentBuilder, MyComponent], (tcb: TestComponentBuilder, myComponent) => {
return tcb.createAsync(MyComponent).then((fixture) => {
fixture.detectChanges();
/**
* my custom stuff
*/
});
})));
});
答案 0 :(得分:3)
您还可以覆盖TestComponentBuilder
本身的提供商。
这是解决方案:
(刚刚覆盖了tcb
)
describe('List view component', () => {
beforeEachProviders(() => {
return [
ROUTER_PROVIDERS,
HTTP_PROVIDERS,
{ provide: RouteParams, useValue: new RouteParams({ query: 'test' }) },
{ provide: MyService, useClass: MockMyService },
MyComponent,
{ provide: APP_BASE_HREF, useValue: '/' }),
{ provide: ROUTER_PRIMARY_COMPONENT, useValue: AppComponent }),
{ provide: ApplicationRef, useClass: MockApplicationRef })
];
});
it('1: component value check',
async(inject([TestComponentBuilder, MyComponent], (tcb: TestComponentBuilder, myComponent) => {
return tcb.overrideProviders(MyComponent, [
{ provide: MyService, useClass: MockMyService }
]).createAsync(MyComponent).then((fixture) => {
fixture.detectChanges();
/**
* my custom stuff
*/
});
})));
});
我希望,这会有所帮助:)