我在我的应用程序中使用商店,如下所示,它工作正常。
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('') 被调用时,它将返回模拟数据。模拟数据返回一个名为 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. 我的测试 我知道这个测试会按照期望语句失败,但我无法用我的模拟数据填充 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 打印 undefined 并且无法读取 MockStore select() 返回的数据。我需要做些额外的事情吗?