Skip to content
Swizec Teller - a geek with a hatswizec.com

How to write tests for XState – CodeWithSwiz 12

Once you know how to refactor a useReducer to XState, you gotta prove you did it right.

CodeWithSwiz is a twice-a-week live show. Like a podcast with video and fun hacking. Focused on experiments. Join live Wednesdays and Sundays

useAuth had existing tests for its core reducer and that makes refactoring easier.

In theory tests are great for refactoring. You can change the implementation, leave tests alone, get them passing. Verify you refactored without destroying the external API.

My tests were not that good.

// src/__tests__/authReducer.spec.ts
describe("login", () => {
const currentTime = new Date().getTime();
const state: AuthState = { // ... };
const action: AuthAction = { // ... };
it("adds user to local storage", () => {
localStorage.removeItem("useAuth:expires_at");
localStorage.removeItem("useAuth:user");
authReducer(state, action);
expect(
JSON.parse(localStorage.getItem("useAuth:expires_at")!)
).toBeGreaterThanOrEqual(currentTime + 500 * 1000);
expect(localStorage.getItem("useAuth:user")).toEqual(
JSON.stringify(action.user)
);
});
it("sets user", () => {
expect(authReducer(state, action).user).toEqual(action.user);
});
it("sets expiresAt", () => {
expect(authReducer(state, action).expiresAt).toBeGreaterThanOrEqual(
currentTime + 500 * 1000
);
});
// ...
});

Beautiful reducer tests. Take reducer as a function, pass-in a fake current state and an action, check for expected changes.

Every part of the reducer's "login" action gets tested.

// src/authReducer.ts
switch (action.type) {
case "login":
const { authResult, user } = action;
const expiresAt =
authResult.expiresIn! * 1000 + new Date().getTime();
if (typeof localStorage !== "undefined") {
localStorage.setItem(
"useAuth:expires_at",
JSON.stringify(expiresAt)
);
localStorage.setItem("useAuth:user", JSON.stringify(user));
}
return {
...state,
user,
expiresAt,
authResult
};

Can you spot the problem?

Testing too close to the implementation

My tests are looking at implementation details. They know how the reducer works and test that way.

That won't work for XState.

XState doesn't let you fake anything. You can't force it into a particular state, you can't trick it to do something it's not supposed to.

That's the whole point. "Make impossible states impossible" as the tagline goes.

How to test XState

As David says in his tweet, the trick is to go one level higher and write better tests. At the integration and API level.

Start by initializing your state machine.

// src/__tests__/authReducer.spec.ts
function initStateMachine() {
const state = interpret(authMachine.withContext(initialContext)).start()
return state
}

You'll use this in multiple tests so having a function helps. It takes your state machine – authMachine – seeds it with initial context and starts an interpreter.

Jest runs tests within a describe block in sequence[1]. That means you can share setup between tests.

// init with values to easily tell TypeScript the type
let authState = initStateMachine(),
savedContext = initialContext
beforeEach(() => {
authState = initStateMachine()
authState.subscribe((state) => {
savedContext = state.context
})
})

Create a shared authState and savedContext, giving them values makes TypeScript's type inference kick in. Means you don't have to specify your own types.

In a beforeEach block you then instantiate a fresh state machine for each test and subscribe to changes. This lets you keep track of the latest application state.

Each test then triggers the right sequence of actions and checks the result.

// src/__tests__/authReducer.spec.ts
describe("LOGIN", // ...
it("sets user", () => {
authState.send("LOGIN");
authState.send("AUTHENTICATED", loginPayload);
expect(savedContext.user).toEqual(loginPayload.user);
});
it("sets expiresAt", () => {
authState.send("LOGIN");
authState.send("AUTHENTICATED", loginPayload);
expect(savedContext.expiresAt).toBeGreaterThanOrEqual(
currentTime + 500 * 1000
);
});
it("sets authResult", () => {
authState.send("LOGIN");
authState.send("AUTHENTICATED", loginPayload);
expect(savedContext.authResult).toBe(loginPayload.authResult);
});

We need 2 actions for each test:

  • LOGIN moves the state machine from unauthenticated to authenticating
  • AUTHENTICATED moves it from the authenticating state into authenticated

The state subscription runs every time and updates savedContext. You can then verify the expected result.

You could move action firing into beforeEach to DRY this up further. I prefer to make it obvious what each test is testing.

Bonus: Clean side effects

Fun bonus from using XState 👉 clean, readable, predictable side-effects.

Look at this login action on the reducer:

case "login":
const { authResult, user } = action;
const expiresAt =
authResult.expiresIn! * 1000 + new Date().getTime();
if (typeof localStorage !== "undefined") {
localStorage.setItem(
"useAuth:expires_at",
JSON.stringify(expiresAt)
);
localStorage.setItem("useAuth:user", JSON.stringify(user));
}
return {
...state,
user,
expiresAt,
authResult
};

Bleh. Deals with local storage, handles time, hard to read. You can't look at this and immediately know what's going on and why.

Compare to the XState version:

authenticated: {
on: {
LOGOUT: "unauthenticated"
},
entry: ["saveUserToContext", "saveToLocalStorage"],
exit: ["clearUserFromContext", "clearLocalStorage"]
},

Ah! When the user enters the authenticatd state, we saveUserToContext and saveToLocalStorage. When they exit this state, we clear.

Methods for that are defined later. Each does 1 thing.

actions: {
saveUserToContext: assign((context, event) => {
const { authResult, user } = event;
const expiresAt =
authResult.expiresIn! * 1000 + new Date().getTime();
return {
user,
authResult,
expiresAt
};
}),
saveToLocalStorage: (context, event) => {
const { expiresAt, user } = context;
if (typeof localStorage !== "undefined") {
localStorage.setItem(
"useAuth:expires_at",
JSON.stringify(expiresAt)
);
localStorage.setItem("useAuth:user", JSON.stringify(user));
}
},

Same code as before but readable and organized. Beautiful 😍

Cheers,
~Swizec

Did you enjoy this article?

Published on October 13th, 2020 in CodeWithSwiz, Livecoding, Technical, XState

Learned something new?
Want to become a high value JavaScript expert?

Here's how it works 👇

Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet 📖right away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

Start with an interactive cheatsheet 📖

Then get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career.

"Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"

~ Ashish Kumar

Join over 10,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

Ready to Stop copy pasting D3 examples and create data visualizations of your own?  Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️