Ngrx 存储调度不接受字符串作为参数
2019-10-10
1050
我正在参加一个测试,其中我应该以这样一种方式编写代码,以便所有单元测试用例都能通过。
案例 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' }) ].
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 超出了教学大纲,我不知道。请帮忙。
2个回答
报告的错误是关于您的测试用例中的
.toHaveBeenCalledWith('movies');
。预期是单词
movies
被用作参数,这是不正确的。
当您在控制器中调用
this.store.dispatch({type: 'movies'});
时,它会将对象
{type: 'movies'>
作为参数传递。
由于您的测试只期望单词
movie
,因此会失败
将您的期望更改为
expect(store.dispatch).toHaveBeenCalledWith({type: 'movies'});
这将修复您的测试
祝您学习顺利
The Fabio
2019-10-11
var data = 'movies'; this.store.dispatch(data as any)
var data = 'movies';
this.store.dispatch(data as any)
您可以通过将字符串转换为任意字符串来实现结果
Somnath
2021-09-02