Reputation: 1488
I have a redux file that contains my reducer and all of my actions via named exports.
export const reducer = (state, action) => ...
export myAction = action => {
return {type: 'ACTION', action}
}
...
When in my test file I import the reducer and the actions. I have a renderWithRedux which takes in the reducer and creates a real store inside.
function renderWithRedux(ui, reducer = combineReducers(reducers), initialState = {}) {
const store = createStore(reducer, initialState)
const utils = render(<Provider store={store}>{ui}</Provider>)
return {
...utils,
store,
}
}
The question I have is that the component I'm rendering is passed actions in the mapDispatchToProps in the connected component.
export default connect(mapStateToProps, { myAction })(MyComponent)
I want to mock the myAction in my particular use case this action would actually be a thunk and I want to see if the store updated.
The problem I have is how do I mock myAction but not the reducer. I've tried
jest.mock('./reducerFile', () => {
return jest.fn().mockImplementation(() => {
return {
reducer: require.requireActual('./reducerFile').reducer,
myAction: jest.fn()
}
})
})
But the reducer is still mocked somehow.
Is this even possible or am I just wanderlust.
Upvotes: 9
Views: 6043
Reputation: 9416
You can try this workaround:
jest.mock('./reducerFile', () => {
const moduleMock = jest.requireActual(
'./reducerFile'
);
return {
...moduleMock,
myAction: jest.fn(),
};
});
Upvotes: 16
Reputation: 2727
You can do something like I did, in your test file:
const yourModule = require('../path/to/yourModule');
yourModule.myFn = jest.fn();
This would mock the named export function in your module.
Upvotes: 0
Reputation: 1368
Unfortunately, you are out of luck. Jest mocks the entire module. It is not possible to partially mock a file. I personally would recommend splitting up the file to make testing easier for you.
See this discussion on github for an in-depth explanation as to why: https://github.com/facebook/jest/issues/936
Upvotes: 0