我正在测试,我应该以这样一种方式编写代码a,以使所有单元测试用例都可以通过。
情况1:
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' }) ].
减速器
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;
};
操作
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超出了教学大纲,我不知道。请帮忙。
答案 0 :(得分:1)
报告的错误大约来自您的测试用例.toHaveBeenCalledWith('movies');
。期望是movies
一词已被用作参数,这是不正确的。
在控制器中调用this.store.dispatch({type: 'movies'});
时,它将传递对象{type: 'movies'}
作为参数。
由于您的测试仅预期单词movie
,所以测试失败
将您的期望更改为
expect(store.dispatch).toHaveBeenCalledWith({type: 'movies'});
这将解决您的测试
祝你学习顺利