Reseed your database with Cypress
There are other possibilities to test a specific scenario, but they all come at a cost:
- Run a previously tested scenario to set up a specific test case, this can be time-consuming to run and to write
- Expose create, update, and delete functions to be able to set up a specific test, with the consequence you end up with "backdoor" functions in an API. To be able to run specific test cases you will write more code (and have more maintenance) to be able to test your code. By exposing these functions there's a possibility they make it to production where they can become harmful if someone finds these backdoor functions
- Because it can be hard/time-consuming to test a specific scenario, some tests will not be written
But what do we gain by reseeding the database?
Well, we can write isolated test cases, this has the benefit that each test case:
- is scoped to a specific test case
- can run individually
- is fast and easy to use
- is reliable
A Cypress task can be registered, the same way as a plugin.
We can listen to tasks when we bind the
task event inside the
To register multiple tasks, we pass an object of our tasks as parameter.
The property names are used to execute the task later on in our tests, and the value must be a
Promise wherein the task logic lives.
We aren't covering the
seed scripts because these will be different based on the chosen stack.
To run the task we can use the
In our case, we want to reseed the database before running each test.
Therefore, we use the
beforeEach hook inside the
By default, a task will timeout after one minute. For most of the cases this will be enough, but for the cases that are taking longer it's possible to change the timeout.
To change it at a global level, change the default timeout inside
Or modify the timeout value on a task level by changing the options.
Please consider supporting me if have you enjoyed this post and found it useful: