Tom MacWright

2025@macwright.com

TIL: Vitest assert

We had a bunch of code like this in our vitest test suite:

expect(createdUser).toBeTruthy();
expect(createdUser?.email).toBe(mockEmail);
expect(createdUser?.profileImageUrl).toBe(mockProfileImageUrl);

This needs the pesky ? optional chaining operator because createdUser is maybe an undefined value. But vitest has that expect() call that makes sure it's truthy, right!

Expectations in vitest aren't also test assertions - maybe for some hard TypeScript reasons or because they can be loose assertions that keep running code, or whatever. Anyway:

vitest provides an assert function that you can use like this:

assert(createdUser, 'User exists');
expect(createdUser.email).toBe(mockEmail);
expect(createdUser.profileImageUrl).toBe(mockProfileImageUrl);

Unlike an expect, assert does tell TypeScript that the code after the assert won't run if the assertion fails, so you can get rid of any optional chaining after that point. Nifty!