Test fixtures
For those who write tests, one of the main problems is fixtures, as they can sometimes be complicated.
To solve related problems, I use several approaches.
- I use builders to construct objects before storing them in the database. This way, I don’t have to write a lot of repetitive code just to configure the necessary fields, and I can also specify only the fields that need to be checked later.
// Here I implicitly set all necesserary fields
// But explicitly I set only the email field, which I'll check later.
const user = getUserBuilder()
.withEmail('test@example.com')
.save();
// ...
expect(user.email).toBe('test@example.com');
- I group tests into suites (usually by domain or context). There, I create sets of fixtures specific to each context.
- I rely on function composition when creating fixtures (I'll write more about this later).
- I don’t think there should be only one fixture per test file, especially when the file contains multiple tests. I usually write a separate fixture for each test. This allows for more atomic and focused tests.