Testing with random values
TLDR; In tests, libraries such as casual can generate random values. This helps improve readability and reduces coupling.
In unit tests, we use placeholder values as input parameters or mocks and expect corresponding return values or side effects in the test process.
Similar placeholder values are often used in a large number of tests.
It then makes sense to outsource their generation to so-called factories.
A factory is simply a function that generates objects.
Especially when the code for generating placeholder values and the code for the tests are separate, it is important that they do not unexpectedly couple against each other.
This can easily happen if a factory does not generate random values but always the same ones.
If these values are then repeated in the test, the test starts to couple against details of the factory.
This is easily noticed by the fact that you can no longer simply change the factory without the test failing.
A simplified example:
// userFactory.js function createUser() %7B return %7B id: 1, name: 'Someone' %7D %7D // user.js function userLabel(user) %7B return `$%7Buser.name%7D ($%7Buser.id%7D)` %7D // user.spec.js it('should display the users name', () => %7B expect(userLabel(createUser())).toMatch('Someone') %7D)
A coupling has arisen here by the double use of
In larger applications, such dependencies can spread over a large number of files. They become more complex and harder to detect.
By generating random data in the Factory above, we can prevent this.
// userFactory.js function createUser() %7B return %7B id: 1, name: casual.name %7D %7D
Tests with a coupling against the name previously used in the factory fail, but can be easily migrated:
// user.spec.js it('should display the users name', () => %7B const user = createUser() expect(userLabel(user)).toMatch(user.name) %7D)
If adjusted in the Factory in the future, the test will respond more robustly.
Besides the reduced coupling, using random data also has the advantage that we don't have to come up with test data like "Hello World".
This then not only makes the tests more robust, but also makes the code more intuitively understandable.