I have the following action that displays a notification and then removes it, and I´m trying to write a unit test for it but I can't seem to figure out how to mock setTimeout.
export const addNotification = (text, notificationType = 'success', time = 4000) => {
return (dispatch, getState) =>{
let newId = new Date().getTime();
dispatch({
type: 'ADD_NOTIFICATION',
notificationType,
text,
id: newId
});
setTimeout(()=>{
dispatch(removeNotification(newId))
}, time)
}
};
export const removeNotification = (id) => (
{
type: 'REMOVE_NOTIFICATION',
id
});
Following the tutorial in the redux website on async testing I came up with the following test:
import * as actions from '../../client/actions/notifyActionCreator'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
const middlewares = [ thunk ];
const mockStore = configureMockStore(middlewares);
describe('actions', ()=>{
it('should create an action to add a notification and then remove it', ()=>{
const store = mockStore({ notifications:[] });
const text = 'test action';
const notificationType = 'success';
const time = 4000;
const newId = new Date().getTime();
const expectedActions = [{
type: 'ADD_NOTIFICATION',
notificationType,
text,
id: newId
},{
type: 'REMOVE_NOTIFICATION',
id: newId
}];
return store.dispatch(actions.addNotification(text,notificationType,time))
.then(() => {
expect(store.getActions()).toEqual(expectedActions)
});
});
});
right now it just throws an error Cannot read property 'then' of undefined at store.dispatch, any help would be greatly appreciated.