0

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?

1
  • 3
    Your testcases should execute all the scenarios in the code basically every line of code should be executed in order to achieve 100% coverage. My guess here is you need to write test case for catch block Commented Oct 20, 2022 at 4:29

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.