I was testing useSelector using the following code below. Although when I looked at my coverage report I saw in red that it wasn't actually being tested... Is there a way to test those lines?
import React from 'react';
import { render } from '../../../test-utlities/test-utlities';
import IndividualInvestor from './IndividualInvestor';
import * as redux from 'react-redux';
describe('Individual Investor', () => {
const useSelectorMock = jest.spyOn(redux, 'useSelector');
const useDispatchMock = jest.spyOn(redux, 'useDispatch');
beforeEach(() => {
useSelectorMock.mockClear();
useDispatchMock.mockClear();
});
test('Makes sure it reaches questionaire', async () => {
useSelectorMock.mockReturnValue({
offering: {
payment_enabled: false,
_id: '61aa480e4e18c1bbfba8f83d',
},
payment_enabled: false,
_id: '61aa480e4e18c1bbfba8f83d',
});
const dummyDispatch = jest.fn();
useDispatchMock.mockReturnValue(dummyDispatch);
CodePudding user response:
Yes, actually run the code :) By mocking useSelector, you've skipped running all of its actual logic that takes your selector function and runs it when needed.
We would strongly recommend against mocking useSelector and useDispatch. Instead, create an actual Redux store in the test, and wrap the component under test with a <Provider>.
You can see examples of how to do this in a reusable render() test util in our docs guide on testing:
https://redux.js.org/usage/writing-tests#components
CodePudding user response:
In addition to what markerikson said i managed to actually test the code with this
wrapper for the component with the provider
// test-utils.js
import React from 'react';
import { render as rtlRender } from '@testing-library/react';
import { configureStore } from '@reduxjs/toolkit';
import { Provider } from 'react-redux';
// Import your own reducer
import rootReducer from '../redux/reducer/combineReducers';
import { BrowserRouter as Router } from 'react-router-dom';
function render(
ui,
{
preloadedState,
store = configureStore({ reducer: rootReducer, preloadedState }),
...renderOptions
} = {}
) {
function Wrapper({ children }) {
return (
<Provider store={store}>
<Router>{children}</Router>
</Provider>
);
}
return rtlRender(ui, { wrapper: Wrapper, ...renderOptions });
}
// re-export everything
export * from '@testing-library/react';
// override render method
export { render };
Then i used that function render
const store = createStore(
rootReducer,
{
formBody: {
offering: {
data: {
payment_enabled: false,
_id: '61aa480e4e18c1bbfba8f83d',
},
},
},
},
applyMiddleware(thunk)
);
const { container } = render( <SomeComponent/>,
//Pass in store here!
{
store: store,
}
);

