我在我的应用程序中使用商店,如下所示,它工作正常。
export class NavigationComponent {
navigationLinks$: Observable<Navigation[]>;
constructor(private store: Store<State>) {
this.navigationLinks$ = this.store.select('navigation')
.map((result: State) => result.navigationLinks);
}
现在,我正在尝试创建一个单元测试,并想要模拟这个商店。这就是我在做的事情:
1。创建模拟商店 创建一个模拟商店,当调用this.store.select(&#39;&#39;)时将返回模拟数据。 mockdata返回一个名为navigationLinks的数组类型的属性。
class StoreMock {
public dispatch(obj) {
console.log('dispatching from the mock store!')
}
public select(obj) {
console.log('selecting from the mock store!');
return Observable.of([
{ 'navigaitonLinks$': [{ 'name': 'Help', hasChild: false}] }
])
}
}
2。 BeforeEach阻止
describe('NavigationComponent', () => {
let component: NavigationComponent;
let fixture: ComponentFixture<NavigationComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [NavigationComponent],
providers: [{provide: Store, useClass: StoreMock}],
imports: [
StoreModule.provideStore(reducers)
],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(NavigationComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
第3。我的测试 我知道这个测试会根据expect语句失败,但是我无法使用我的模拟数据填充navigationLinks $属性。
it(`should create the navigation with 'Help' link`, () => {
let navLinks: any[];
component.navigationLinks$.subscribe();
console.log(navLinks); // This should print my mockdata so i can assert it
expect(component.navigationLinks$).toEqual('Help');
});
console.log打印未定义,无法读取MockStore select()返回的数据。我还需要做些什么吗?
答案 0 :(得分:1)
我有同样的问题,我只是用Observable.of()函数返回对象。
SELECT * FROM (
SELECT subject, MIN(created) AS mintime FROM data_new GROUP BY subject
) AS mintimes INNER JOIN data_old
ON data_old.subject = mintimes.subject AND data_old.created < mintimes.mintime;
到
return Observable.of([
{ 'navigaitonLinks$': [{ 'name': 'Help', hasChild: false}] }
])
这将填充您的Observable对象:
return Observable.of([{ 'name': 'Help', hasChild: false}, {}, {} ... ]);