Reputation: 2970
Hi I have a function as shown below:
MyComponent.js-------
const somefunction = () => {
if (someCondition) {
dispatch(someActionMethod({
id: 01,
empName: 'Adam'
}).then((result) => {
setSomeState(result.data);
})
)
}
}
Tried a lot of ways to mock someActionMethod with dispatch, but all efforts are failing.
My test file:
import React from 'react';
import * as redux from 'react-redux';
import { render } from '@testing-library/react';
const useDispatchSpy = jest.spyOn(reactRedux, 'useDispatch');
const mockDispatchFn = jest.fn();
describe('<MyComponent />', () => {
const props = {};
mockDispatchFn.mockReturnValue(
[{data1},{data2}]
);
let componentRendering;
beforeEach(() => {
componentRendering = render(
<MyComponent props={ props } />
)});
it('test component', ()=> {
expect(componentRendering.container.innerHTML).not.toBeNull();
});
});
Throws me error:
Cannot read properties of undefined (reading 'then')
Upvotes: 0
Views: 8102
Reputation: 787
Are you using it with middleware? I am not sure that dispatch returns a promise nor any value without using middleware.
By the way, mocking a react redux hook is not a recommended way and you could actually see it is not even possible as of version 8 of react-redux package.
Upvotes: 1
Reputation: 443
My assumption from the error message is that your code is expecting a promise somewhere.
The stack trace will have info about the component throwing this error at a specific line.
I would recommend you to check your code and mock all the required methods
I hope this helps in resolving the error
Upvotes: 1
Reputation: 1738
Have you tried to mock useDispatch
instead mocking someActionMethod
?
import * as redux from 'react-redux';
const useDispatchSpy = jest.spyOn(redux, 'useDispatch');
const mockDispatchFn = jest.fn();
// One of these should work
mockDispatchFn.mockReturnValue([{data1}, {data2}]);
useDispatchSpy.mockReturnValue(mockDispatchFn);
With your updated response I'd try this:
describe('<MyComponent />', () => {
it('test component', () => {
const props = {};
const useDispatchSpy = jest.spyOn(reactRedux, 'useDispatch');
const mockDispatchFn = jest.fn();
mockDispatchFn.mockReturnValue(
[{ data1 }, { data2 }],
);
render(<MyComponent {...props} />);
// your assertions here
});
});
Upvotes: 1