I have updated my functional component to now include mapDispatchToProps
alongside the mapStateToProps
that was already in place.
So far I have been able to test my component with React Testing Library successfully, but now with the addition of the mapDispatchToProps
, even my simple tests aren't getting to the correct part of my code. I know this is because my mapDispatchToProps
function isn't being called as I haven't included it in the test file... I'm just curious how I would go about doing this, as I can't seem to find anything online to help.
Component
const mapStateToProps = ({data}) => ({
isDataLoaded: !!data
});
const mapDispatchToProps = dispatch => ({
getData: () => {
dispatch(getFromApi()); // Response will populate data in the mapStatesToProps
}
});
const MyComponent = ({isDataLoaded, getData}) => {
if (!isDataLoaded) {
getData();
}
return isDataLoaded
? <div data-testid="main">/* Data has loaded screen */</div>
: <div data-testid="main">/* Loading screen */</div>
}
MyComponent.propTypes = {
isDataLoaded: PropTypes.bool
}
MyComponent.defaultProps = {
isDataLoaded: false
}
Before I had introduced my dispatch event, I could test with something like this:
const getProvider = (Component, store = null, props) => {
const mockStore = configureStore();
return <Provider store={mockStore(store)}><Component {...props}/></Provider>;
};
const configState = (data = null) => ({
data: data
});
describe('Component tests', () => {
it('Should render loading screen', () => {
provider = getProvider(MyComponent, configState());
rendered = render(provider);
expect(rendered.queryByTestId('main').textContent).toBe(/* LOADING TEXT */);
});
it('Should render data loaded screen', () => {
provider = getProvider(MyComponent, configState(true));
rendered = render(provider);
expect(rendered.queryByTestId('main').textContent).toBe(/* DATA LOADED TEXT*/);
});
});
I'm just not sure how one would go about accessing/mocking the dispatch part, in order to check that the code is still working...
Aucun commentaire:
Enregistrer un commentaire