gpt4 book ai didi

Angular2/测试 : how to run test with mock service provider?

转载 作者:太空狗 更新时间:2023-10-29 18:26:44 25 4
gpt4 key购买 nike

Angular2 测试

我想使用模拟服务而不是实际服务来运行我的组件。我在 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
*/
});
})));

});

最佳答案

您还可以覆盖 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
*/
});
})));

});

我希望,这会有所帮助:)

关于Angular2/测试 : how to run test with mock service provider?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37765692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com