我想测试一个具有一些依赖项的简单组件。因此,除其他外,我必须提供一些提供商 describe('AccountLookupComponent', (( => { let 组件:帐户查找组件; 让夹具: 组件夹具 enter code here
;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
TestComponentWrapper,
AccountLookupComponent
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
imports: [HttpModule],
providers: [AccountLookupService, AuthHttp, AuthenticationService, AdalService, AdfsSecretService, CookieService, NgModule,
{ provide: 'IAccountLookupClient', useClass: AccountLookupClient },
{ provide: 'IApiClient', useClass: ApiClient },
{ provide: 'ITimeoutService', useClass: TimeoutService },
]
})
.compileComponents();
fixture = TestBed.createComponent(TestComponentWrapper);
component = fixture.debugElement.children[0].componentInstance;
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
});
@Component({
selector: 'test-component-wrapper',
template: `<account-lookup filterCurrentAccount="true"
[useAccountIdSearch]="true"
[useCompactResults]="true"
(accountSelected)="null"
placeholder="Find account">
</account-lookup>`,
})
class TestComponentWrapper {
}
从数组中删除NgModule
providers
。它是装饰器。不应将其用作令牌。
export function makeDecorator(
name: string, props?: (...args: any[]) => any, parentClass?: any,
chainFn?: (fn: Function) => void): (...args: any[]) => (cls: any) => any {
const metaCtor = makeMetadataCtor(props);
function DecoratorFactory(objOrType: any): (cls: any) => any { // => here is your provider
有两种方法可以使用提供程序测试组件
1.注入真正的服务。
2. 使用测试替身(存根、假货、间谍或模拟(。
第一种方法 组件不必注入实际服务,但您可以执行类似示例的操作:
TestBed.configureTestingModule({
declarations: [ ExampleComponent ],
providers: [ ExampleService ]]
});
另一种方法是使用存根示例:
TestBed.configureTestingModule({
declarations: [ ExampleComponent ],
// Provide a test-double instead
providers: [ {provide: ExampleService, useValue: exampleServiceStub }]
});
// UserService from the root injector
exampleService = TestBed.get(ExampleService);