如何测试使用setTimeout调用另一个操作的异步操作创建器

时间:2017-03-02 18:14:58

标签: javascript redux jestjs redux-thunk redux-mock-store

我有以下操作显示通知然后删除它,我正在尝试为它编写单元测试,但我似乎无法弄清楚如何模拟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)
                });
        });
    });

现在它只是抛出一个错误无法读取store.dispatch中未定义的属性'then',任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:4)

首先,由于您的操作创建者未返回任何内容,因此当您致电store.dispatch(actions.addNotification())时,它会返回undefined,这就是您收到错误Cannot read property 'then' of undefined的原因。要使用.then(),它应该返回一个承诺。

因此,您应该修复您的动作创建者或测试以反映动作创建者实际执行的操作。要使测试通过,您可以将测试更改为以下内容:

// set up jest's fake timers so you don't actually have to wait 4s
jest.useFakeTimers();

store.dispatch(actions.addNotification(text,notificationType,time));
jest.runAllTimers();
expect(store.getActions()).toEqual(expectedActions);

另一种选择是使用详细的策略in the Jest docs

// receive a function as argument
test('should create an action to add a notification and then remove it', (done)=>{

    // ...

    store.dispatch(actions.addNotification(text,notificationType,time));
    setTimeout(() => {
      expect(store.getActions()).toEqual(expectedActions);
      done();
    }, time);
});

使用此策略时,Jest将等待done()被调用,否则在完成测试主体的执行时它将考虑测试结束。