我有以下显示通知然后将其删除的操作,并且我正在尝试为其编写单元测试,但我似乎无法弄清楚如何模拟 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
});
按照 redux 网站上关于异步测试的教程,我提出了以下测试:
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)
});
});
});
现在它只是抛出一个错误Cannot read property 'then' of undefined at store.dispatch,任何帮助将不胜感激。