javascript - 如何测试使用 setTimeout 调用另一个 Action 的异步 Action 创建者

标签 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)
                });
        });
    });

现在它只是抛出一个错误 Cannot read property 'then' of undefined at store.dispatch,任何帮助将不胜感激。

最佳答案

首先,因为你的 action creator 不返回任何东西,当你调用 store.dispatch(actions.addNotification()) 它返回 undefined 这就是你的原因收到错误 Cannot read property 'then' of undefined。要使用 .then(),它应该返回一个 promise。

因此,您应该修复 Action 创建者或测试以反射(reflect) Action 创建者实际执行的操作。为了让你的测试通过,你可以把你的测试改成这样:

// 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() 被调用,否则它会在测试主体执行完成时认为测试结束。

关于javascript - 如何测试使用 setTimeout 调用另一个 Action 的异步 Action 创建者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42562891/

相关文章:

javascript - 告诉 Firebug 在执行任何 Javascript 后立即中断

javascript - 在 Canvas 上的形状上方显示图像

javascript - 在 Redux 中设置应用挂载的存储状态

javascript - 在 VS Code 中使用 Node shim 调试 React Native

javascript - 如何在 JavaScript 中为 JSON 数组中的每个对象添加 ID?

javascript - jssor 目标幻灯片在另一个页面/文档中

javascript - onClick 事件在 React redux ToDoList 应用程序中未触发

javascript - localStorage突然坏了

reactjs - React 组件上的 Jest 测试 : Unexpected token "<"

javascript - 为什么更改 testMatch 正则表达式时 Jest 覆盖率报告会中断?