I am trying to test a functional component which is below :
export const MyFunctionalComponent=()=>{
const {id, otherid} = useSelector((state) => state.user);
const accounts = useSelector((state) => state.Selection.accounts);
const dispatch = useDispatch();
useEffect(() => {
if (!accounts) {
dispatch(getDetails(id, otherid));
}
}, []);
const handleOnClick = (Id) => {
dispatch(saveId(Id));
};
if (!accounts) {
return <CircularLoader />;
}
if (!accounts.length) {
return (
<AccessUnavailablePanel
/>
);
}
if (accounts.length === 1) {
return <Redirect to={`${accounts[0].id}`} />;
}
return (
<MyList
accounts={accounts}
handleOnClick={handleOnClick}
/>
);
};
i am new to JEST , how can i correctly mock useSelector, useDispatch and useEffect ?
i am trying to test as follows :
jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useSelector: jest.fn(),
useDispatch: jest.fn()
}));
describe('<MyFunctionalComponent/>', () => {
const useEffect=jest.spyOn(React, "useEffect").mockImplementation(() => {})
const useSelectorMock = reactRedux.useSelector;
const useDispatchMock = reactRedux.useDispatch;
const user = {
id: '32sdfsdfr-fjdfdk33-4434sdfs',
otherid: '73587hdfjg-dfghd94-jgdj'
};
const store = mockStore({
user:user,
Selection: {
Id: '',
accounts: null
}
});
let wrapper;
const setup = () => {
const {result} = renderHook(() => MyFunctionalComponent(), {
wrapper: ({children}) => (
<Provider store={store}>{children}</Provider>
)
});
return result;
};
describe('Rendering accounts available', () => {
beforeEach(() => {
useDispatchMock.mockImplementation(() => () => {});
useSelectorMock.mockImplementation((selector) =>
selector(mockStore)
);
});
afterEach(() => {
jest.clearAllMocks();
useSelectorMock.mockClear();
useDispatchMock.mockClear();
});
it('should render the accounts if more than 1 account available', () => {
useSelectorMock.mockReturnValue(user);
const mockdata = {
accounts: [
{
id: '637ghgh',
},
{
id: '10a190abd',
}
]
};
const getDetails = jest.spyOn(
SelectionActions,
'getDetails'
);
useSelectorMock.mockReturnValue(mocdata);
useDispatchMock.mockReturnValue(
getDetails(user.id, user.otherid)
);
wrapper = setup();
store.dispatch(getDetails(user.id, user.otherid))
sleep(500);
const actions=store.getActions();
console.debug(actions[0])
expect(getDetails).toHaveBeenCalledWith(user.id, user.otherid);
expect(actions[0].type).toEqual('GET_DETAILS')
expect(wrapper.current).toMatchSnapshot();
});
});
But my snapshot seems to return AccessUnavialable, and the payload is undefined. How can I modify my tests to correctly return the mocked data as payload and get the correct snapshot?
useEffectneitheruseDispatchsince you've wrapped the component in aProvider. Also, shouldn'tmockdatabe an array?