Reseed your database with Cypress

profile
Tim Deschryver
timdeschryver.dev

By using a Cypress task it's possible to run code JavaScript code in Node.js. We can leverage this API to reseed a database with data we're in control of. Having control over the data allows us to write specific scenarios to run tests against.

There are other possibilities to test a specific scenario, but they all come at a cost:

Why link

But what do we gain by reseeding the database?

Well, we can write isolated test cases, this has the benefit that each test case:

How link

Creating the task link

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 plugins/index.js file. 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 teardown and seed scripts because these will be different based on the chosen stack.

Running the task link

To run the task we can use the cy.task(taskName) method. In our case, we want to reseed the database before running each test. Therefore, we use the beforeEach hook inside the support/index.js file.

Modifying the timeout time link

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 cypress.json.

Or modify the timeout value on a task level by changing the options.

Incoming links

Feel free to update this blog post on GitHub, thanks in advance!

Join My Newsletter (WIP)

Join my weekly newsletter to receive my latest blog posts and bits, directly in your inbox.

Support me

I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.

Buy Me a Coffee at ko-fi.com PayPal logo

Share this post

Twitter LinkedIn