我正在参加一个测试,我应该以所有单元测试用例都通过的方式编写代码。
案例一:
it('should dispatch action when dispatchAction is called', async() => {
// you need to spy on store's 'dispatch' method
store = TestBed.get(Store);
spyOn(store, 'dispatch').and.callThrough();
// if you call function dispatchAction with 'movies' paramter. expect store to dispatch action='movies'
component.dispatchAction('movies');
fixture.detectChanges();
expect(store.dispatch).toHaveBeenCalledWith('movies');
});
我的代码:
dispatchAction($event: string) {
this.store.dispatch({type: 'movie'});
}
但是规范失败并抛出以下错误
Expected spy dispatch to have been called with [ 'movies' ] but actual calls were [ Object({ type: 'movies' }) ].
reducer ,
export function news (state = initialState, action: Action) {
switch (action.type) {
case LOAD_SECTION_NEWS: {
return {
newsList: mockNewsList,
filter: action.type
};
}
case FILTER_SUBSECTION: {
return {
newsList: mockNewsList,
filter: action.payload
};
}
default:
return state;
}
}
export const getNewsList = (state: any) => {
return state;
};
export const getFilter = (state: any) => {
return state;
};
Action
export class NewsActions {
static LOAD_SECTION_NEWS = '[News] LOAD_SECTION_NEWS';
static FILTER_SUBSECTION = '[News] FILTER_SUBSECTION';
LoadSectionNews(list: News[]): Action {
return {
type: '',
payload: ''
};
}
FilterSubsection(subsection: string) {
return {
type: '',
payload: ''
};
}
}
我如何修改 reducer 以使单元测试用例通过。
这个 Ngrx 超出了教学大纲,我不知道。请帮忙。
最佳答案
报告的错误与您的测试用例中的 .toHaveBeenCalledWith('movies');
有关。期望单词 movies
被用作参数,这是不正确的。
当您在 Controller 中调用 this.store.dispatch({type: 'movies'});
时,它会传递对象 {type: 'movies'}
作为参数。
因为您的测试只需要单词 movie
,所以它失败了
改变你的期望
expect(store.dispatch).toHaveBeenCalledWith({type: 'movies'});
这将修复你的测试
祝你学业顺利
关于javascript - Ngrx store dispatch 不接受字符串作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58329229/