ryu
ryu

Reputation: 43

Testing react component to get 100% coverage

I am learning react testing library and jest. For now I'm writing a component to update data from the database. The code looks like this:

const UseUpdateData = ({id, status}) => {
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(false);
    const [updatedStatus, setUpdatedStatus] = useState(status);

    const update = async () => {
        setError(false);
        setLoading(true);

        try {
            const updateBillStatusTo =
                updatedStatus === "PAID" ? "PENDING" : "PAID";

            const response = await fetch(...);

            const updatedBillStatus = response.data;

            setLoading(false);
            setUpdatedStatus(updatedBillStatus);
        } catch {
            setLoading(false);
            setError(true);
        }
    };

    return { loading, error, updatedStatus, update };
};
return default UseUpdateData;

The update function will be called from another component when a button is clicked. When I write test to this component, I only get 50% coverage on Branch. Is this component usage is wrong? That's why I can't get 100% coverage?

Upvotes: 0

Views: 85

Answers (1)

pachun
pachun

Reputation: 920

Without seeing your test, it's tough to say for sure, but it's probably because you're not testing the catch block of your try/catch statement; eg the two lines:

setLoading(false);
setError(true);

aren't being run by your test suite. To test those two lines, you'll want another test that simulates what would truly cause the catch block to be executed. So - why did you put this logic in the try block?

            const updateBillStatusTo =
                updatedStatus === "PAID" ? "PENDING" : "PAID";

            const response = await fetch(...);

            const updatedBillStatus = response.data;

            setLoading(false);
            setUpdatedStatus(updatedBillStatus);

What in there do you expect might fail? For now I'll assume you expect that the fetch might fail. The reason why it might fail would be a good title for your new test case. In that test case, mock fetch to raise the error you expect to get in the case where fetch fails IRL. Maybe to see what that is, you can turn off your wifi and run the code to see what fetch returns and then mock fetch in your test to return that value.

Here's how you might mock fetch to test the catch block of your code.

Upvotes: 1

Related Questions