When to use @xstate/test
When you discover a new tool, it’s tempting to use that tool for everything. Model-based testing is good for many use cases but not for all use cases.
Let’s explore what makes a good candidate for model-based testing.
Long setup
@xstate/test
is most useful when what you’re testing requires a lengthy, complex setup. For example, if you were manually testing a multi-step form, you might need to input the same fields again and again to perform the tests.
In these situations, @xstate/test
shines because it can automate a lot of the setup for you over multiple tests.
However, many tests require no setup at all. Take the following function for example:
const add = (a: number, b: number) => {
return a + b;
};
The add
function requires no setup whatsoever and can be tested as follows:
it('Should add numbers together', () => {
expect(add(1, 2)).toEqual(3);
});
In general, you should avoid using model-based testing in situations that require no setup.
Examples of long setups
- Testing frontend applications that can be in complex states.
- Testing backend methods where the database needs to be set up into a certain state before it can be tested.
- Testing flows with mocked dependencies which need to be set up in different ways before assertions are run.
Examples of short setups
- Testing pure functions which take in an input and return a predictable output without firing side effects.