7

我有以下显示通知然后将其删除的操作,并且我正在尝试为其编写单元测试,但我似乎无法弄清楚如何模拟 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,任何帮助将不胜感激。

4

1 回答 1

8

首先,由于您的动作创建者不返回任何内容,因此当您调用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);

另一种选择是使用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()被调用,否则会在测试体执行完毕时认为测试结束。

于 2017-03-02T18:46:41.677 回答