问题的解决方法是在测试组件的之前手动创建mock store。在创建mock store之前,将使用的spies和mock selectors设置为初始值。然后创建一个mock store实例来传递到测试组件中。
下面是一个示例代码:
import { provideMockStore } from '@ngrx/store/testing';
describe('Component', () => {
let store: MockStore;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ ... ],
providers: [
provideMockStore({ initialState }),
// other providers
]
});
store = TestBed.inject(MockStore);
// set up the spies and selectors here with initial values
});
it('should display the correct value from the store', () => {
const expectedValue = 'foo';
// update the mock store with the expected value
store.setState({ value: expectedValue });
// create the component to test here
const fixture = TestBed.createComponent(Component);
const component = fixture.componentInstance;
fixture.detectChanges();
// assert that the component displays the expected value
expect(component.value).toBe(expectedValue);
});
});