Jest mocking - 模拟命名导出,除了一个

Jef*_*rdt 5 jestjs react-redux react-testing-library

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

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

export myAction = action => {
    return {type: 'ACTION', action}
}
...
Run Code Online (Sandbox Code Playgroud)

在我的测试文件中,我导入了减速器和操作。我有一个 renderWithRedux,它接收 reducer 并在里面创建一个真正的store。

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

    return {
        ...utils,
        store,
    }
}
Run Code Online (Sandbox Code Playgroud)

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

export default connect(mapStateToProps, { myAction })(MyComponent)
Run Code Online (Sandbox Code Playgroud)

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

我的问题是如何模拟 myAction 而不是减速器。我试过了

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

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

这是可能的还是我只是流浪癖。

Krz*_*bek 10

您可以尝试以下解决方法:

jest.mock('./reducerFile', () => {
  const moduleMock = jest.requireActual(
    './reducerFile'
  );

  return {
    ...moduleMock,
    myAction: jest.fn(),
  };
});
Run Code Online (Sandbox Code Playgroud)


tpd*_*etz 0

不幸的是,你运气不好。Jest 嘲笑整个模块。无法部分模拟文件。我个人建议拆分文件以使测试更容易。

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