Soft assertions
The software you build tends to get complex, which is a direct reflection of the complexity behind its requirements. Sometimes, you have multiple expectations toward your system even within a single test case (which, by the way, I find to be absolutely normal).
For example, let's say you are testing a user subscription service. There, one of the expectations is that when the user cancels their subscription, their
user.subscription
object must transition to the correct state:user.cancelSubscription()
expect(user.subscription.state).toBe('cancelled')
expect(user.subscription.endsAt).toBe('2025-01-01T00:00:00.000Z')
There are two criteria to assume the correct cancellation:
- The
state
property equals to'cancelled'
; - The
endsAt
property equals to the first day of the next month after the subscription has been cancelled.
You refelect these criteria in individual
expect()
calls (i.e. assertions).There is a great deal of value to be had from how your tests fail. In fact, most of the decisions you make when writing your tests comes down to designing a nice experience around test failures, one way or another.
So, what happens when our subscription test fails?
Right now, it can fail when either of the assertions fails (incorrect state update) or both of them fail (missing state transition from
active
to cancelled
). In any case, its failure indicates a problem and must help you get to its root cause faster.Let's imagine this test fails because the subscription never transitioned from
active
to cancelled
. Your first piece of feedback from the test will be this:AssertionError: expected 'active' to be 'cancelled'
Expected: "cancelled"
Received: "active"
This is a useful feedback as it clearly indicates an incorrect (or missing) state transition.
But it doesn't tell you the whole picture.
It only tells you the result of the first failed assertion. What about the other expectations? Did they succeed or also failed? Was the
endsAt
date calculated correctly, if at all? What if you have three, five, or ten assertions toward the same state? How did those fare?All of that information is important when debugging issues. But since assertions are sensitive to order and operate on the fail-fast principle, you are locking yourself in a minigame of addressing failed assertions one-by-one instead of grasping the issue as a whole.
Your task
Let's change that.
👨💼 In this one, you will refactor this user subscription test to use soft assertions. It's the kind of assertion that still runs and gives value but doesn't short-circuit the test if it fails. Head straight to and follow the instructions to refactor the test and gain more value out of its failures.
👨💼 Bonus points if you track down and fix the issue to have the tests passing.