Reputation: 79
I'm taking a test in which I should write code a in such a way that all unit test case gets passed.
Case 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');
});
My code:
dispatchAction($event: string) {
this.store.dispatch({type: 'movie'});
}
But the spec is getting failed throwing the below error
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: ''
};
}
}
How do I modify, the reducer in such a way that the unit test case get passed.
This Ngrx is out of syllabus and I've no idea. Please help.
Upvotes: 1
Views: 1120
Reputation: 1
var data = 'movies'; this.store.dispatch(data as any)
var data = 'movies';
this.store.dispatch(data as any)
You can achieve the result by casting the string to any
Upvotes: 0
Reputation: 6260
The error reported is about .toHaveBeenCalledWith('movies');
from your test case. The expectation is the word movies
to have been used as argument, and this is incorrect.
When you call this.store.dispatch({type: 'movies'});
in your controller, it is passing the object {type: 'movies'}
as argument.
as your test is expecting only the word movie
, it fails
change your expectation to
expect(store.dispatch).toHaveBeenCalledWith({type: 'movies'});
that will fix your test
Good luck with your studies
Upvotes: 1