在Angular Jasmine测试中,为具有不同泛型类型的同一类使用两个提供程序



我正试图为注入到我的组件中的类创建两个不同的mock提供程序和spy。依赖项是同一个类,但使用不同的类型,使用泛型。

constructor(
private readonly languageStore: Store<fromLanguageStore.LanguageState>,
private readonly userStore: Store<fromUserStore.UserState>) {}

组件.ts

我试过以下几种;

providers: [
{
provide: Store<fromLangaugeStore.LanguageState>,
useValue: languageStoreMock
},
{
provide: Store<fromUserStore.UserState>,
useValue: userStoreMock
}
]

组件规格

在等级库文件中,无法执行上述操作。我还尝试过使用一个提供程序,并使用类似的spyOn;

spyOn(storeMock, 'pipe').and.callFake((func) => {
//
})

但是传入该方法的是'@ngrx/store'中的select((函数,我看不出如何根据该方法切换fake返回的内容,因为它们都传递了select,但参数不同,即

this.languageStore.pipe(select(fromLanguageStore.getLanguageContext))
this.userStore.pipe(select(fromUserStore.getUserContext))

在组件中注入Store两次,这对我来说很奇怪。我只会像这样注入一次:

constructor(
private readonly store: Store<fromLanguageStore.LanguageState | fromUserStore.UserState>) {}

商店是一个数据库,任何时候你需要languageState,你都可以做:

languageState$ = this.store.select(....); // select the language state from the store
userState$ = this.store.select(....); // select the user state from the store

这样,您只需要为Store创建一次mock。

编辑

我提供存储并进行集成测试,以模拟存储的不同部分。

TestBed.configureTestingModule({
declarations: [AppComponent, BookListComponent, BookCollectionComponent],
imports: [
HttpClientTestingModule,
StoreModule.forRoot({
books: booksReducer,
collection: collectionReducer,
}),
],
providers: [GoogleBooksService],
}).compileComponents();

fixture = TestBed.createComponent(AppComponent);
component = fixture.debugElement.componentInstance;
store = TestBed.inject(Store);  // get a handle on the store
store.dispatch(new SetUsers(...)); // put the users you want in the ...
store.dispatch(new SetLanguage(...)); // put the language state you want in the ... // after doing the above lines, your store should be populated with what you want
fixture.detectChanges();

查看此链接。

最新更新