Jest嘲笑 - Mock将其命名为除了一个

问题描述 投票:1回答:2

我有一个redux文件,其中包含我的reducer和我通过命名导出的所有操作。

export const reducer = (state, action) => ...

export myAction = action => {
    return {type: 'ACTION', action}
}
...

在我的测试文件中,我导入reducer和动作。我有一个renderWithRedux,它接收reducer并在里面创建一个真正的商店。

function renderWithRedux(ui, reducer = combineReducers(reducers), initialState = {}) {
    const store = createStore(reducer, initialState)
    const utils = render(<Provider store={store}>{ui}</Provider>)

    return {
        ...utils,
        store,
    }
}

我的问题是我正在渲染的组件是在连接组件的mapDispatchToProps中传递的操作。

export default connect(mapStateToProps, { myAction })(MyComponent)

我想在我的特定用例中模拟myAction,这个动作实际上是一个thunk,我想知道商店是否更新。

我遇到的问题是如何模拟myAction而不是reducer。我试过了

jest.mock('./reducerFile', () => {
    return jest.fn().mockImplementation(() => {
        return {
            reducer: require.requireActual('./reducerFile').reducer,
            myAction: jest.fn()
        }
    })
})

但减速器仍然以某种方式嘲笑。

这甚至是可能的还是我只是徘徊。

react-redux jestjs react-testing-library
2个回答
0
投票

不幸的是,你运气不好。 Jest嘲笑整个模块。无法部分模拟文件。我个人会建议拆分文件,以便您更轻松地进行测试。

请参阅github上的讨论,深入解释原因:https://github.com/facebook/jest/issues/936


0
投票

您可以在测试文件中执行类似我的操作:

const yourModule = require('../path/to/yourModule');

yourModule.myFn = jest.fn();

这将模拟模块中的命名导出函数。

© www.soinside.com 2019 - 2024. All rights reserved.