【问题标题】:How to understand and unit test this React-Redux function with Jest如何用 Jest 理解和单元测试这个 React-Redux 函数
【发布时间】:2017-09-10 23:12:56
【问题描述】:

我是 React 和 Redux 的新手,我正在开发的模块中有几个函数,

function showDialogAction(): Action {
    return {
        type : SHOW_DIALOG
    };
}

function showDialog() { 
    return (dispatch : (action : Action) => void) => {
        dispatch(showDialogAction());
    };
}

现在我需要为showDialog() 函数编写一个单元测试。我仍然很难理解它到底做了什么。是returning a function that accepts Action and returns void ?? Or ...

如果有人能解释它的工作原理以及任何测试它的建议,我将不胜感激。

【问题讨论】:

    标签: reactjs redux jestjs


    【解决方案1】:

    它返回一个以dispatch 函数为参数的函数,并以showDialogAction 的结果调用它。

    因此,在dispatch : (action : Action) => void 类型的形式中,dispatch 是一个函数()=>,它从类型Action (action : Action) 获取参数action,并且不返回任何内容(@ 987654329@)

    最简单的测试方法是使用dispatch 的间谍:

    const dispatch = jest.fn()
    showDialog()(dispatch) 
    expect(dispatch).toHaveBeenCalledWith({type : 'SHOW_DIALOG'})
    

    【讨论】:

    • 感谢您的解释。你能解释一下dispatch : (action : Action) => void是什么,为什么会有action : Action?可能会更新答案
    • 更新了类型说明
    猜你喜欢
    • 2020-05-03
    • 2020-11-20
    • 2019-03-22
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2019-02-03
    • 1970-01-01
    相关资源
    最近更新 更多