Ngrx 存储调度不接受字符串作为参数



我正在参加一个测试,在这个测试中,我应该以这样一种方式编写代码,以便所有单元测试用例都通过。

案例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: ''
};
}
}

我如何修改化简器,使单元测试用例通过。

这个Ngrx超出了教学大纲,我不知道。请帮忙。

报告的错误与测试用例.toHaveBeenCalledWith('movies');。期望是movies这个词被用作论据,这是不正确的。

当您在控制器中调用this.store.dispatch({type: 'movies'});时,它会将对象{type: 'movies'}作为参数传递。

由于您的测试只期望单词movie,因此失败

将您的期望更改为

expect(store.dispatch).toHaveBeenCalledWith({type: 'movies'});

这将修复您的测试

祝你学习顺利

var data = 'movies'; this.store.dispatch(data as any(

var data = 'movies';
this.store.dispatch(data as any)

您可以通过将字符串强制转换为任何

最新更新