JS: Advanced Testing
Theory: Fixtures
Imagine a function that takes some HTML as input, extracts all the links from it, and returns them as an array:
The piece of HTML at the beginning of the test looks scary. It's large and consists of a massive load of tags. Of course, you can try to format it, but you'll have to do it all manually. For any editor, it's just a line in JavaScript. But it's not just about formatting, this way of working with large chunks of data has other disadvantages:
- It's very easy to make a mistake when preparing updates, and they're difficult to detect visually. The editor can't help here either.
- The more such data in tests, the harder it is to read and separate the logic from the data itself.
It would be much more convenient if HTML was stored as normal HTML in its own file. It isn't hard to do. In this case, the test will look like this:
The data needed during test runs are called fixtures. It isn't necessarily text data. Fixtures can be images, JSON- and XML-files, database records, and more. Sometimes code can also be part of the fixture, but this is quite rare. Such fixtures are needed when testing different code analyzers, such as ESLint or Babel.
Usually, fixtures are stored in separate files in their own directory. In Jest, it's recommended to create a __fixtures__ directory in the root of the project for this purpose. They're then read and used as and when.
An example:
When there's more than one fixture, many similar calls that read files will start to appear in the test code:
In this case, it is better to bring the construction of the path in a separate function, and at the same time use the correct way of gluing paths:

