Higher-order functions

Now, let's look at one the most common scenarios. Suppose that we have a container component called AlertContainer that connects with React components using the connect function. This should not appear alien to you by now:

import React, { Component } from "react";
import { connect } from "react-redux";
import Alerts from "./Alerts";
class AlertContainer extends Component {
componentDidMount() {
this.props.dispatch({ type: "REQUEST_ALERTS_LISTS" });
}
render() {
return <Alerts />;
}
}
export default connect()(AlertContainer);

We have simply used the connect function from react-redux to connect a React component. The Alert components can be as simple as the following:

import React from "react";
const Alerts = () => (
<ul>
<li>This is notification one.</li>
<li>This is notification two.</li>
</ul>
);
export default Alerts;

We are leaving how to test Alert components to you. Now, let's test the AlertContainer.js file. Create the test file, AlertContainer-test.js, as follows:

import React from "react";
import renderer from "react-test-renderer";
import AlertContainer from "../AlertContainer";
jest.mock("react-redux", () => ({
connect: () => obj => obj
}));
jest.mock("../Alerts", () => "Alerts");
it("should render correctly", () => {
const dispatch = jest.fn();
const component = renderer.create(<AlertContainer dispatch={dispatch} />);
expect(component.toJSON()).toMatchSnapshot();
expect(dispatch).toHaveBeenCalled();
expect(dispatch.mock.calls).toMatchSnapshot(
"dispatch function was called correctly"
);
});

It is getting confusing, huh? Well, most of the code should make sense to you, except for the mocking of react-redux. The connect function from react-redux is a very complex function, with several functionalities. In our container component, we are using the connect function to link our container component to the Alert component. So, from Redux, I am just consuming the connect function. As we mentioned before, we can assume that third-party libraries are well tested and correct. Assuming that the react-redux library is well tested, we can safely mock react-redux. In our AlertContainer component, we are only using the connect function. So, we just mocked the entire redux-library, saying that it has a connect function, which is simply a function. Jest provides jest.fn() to mock a function (https://jestjs.io/docs/en/mock-functions). You may have questions, such as: What if we are using other functions? Well, in any container, we are not likely to use all of the functions. So, we can mock the functions used in the container. Moreover, there are other ways that you can mock react-redux. Try to explore those other ways.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset