When I first started using Cypress, I wanted to make it easier to write setup-code for our integration tests.
Cypress comes with cy.task()
which allows us to execute code in a Node.js context, which is
useful if you need to – for example – insert records into a database before a test runs.
What was missing for my taste, was some kind of a namespacing solution (all Cypress tasks live in a global namespace), as well as a place to put all those test setups.
cypress-routines is a tiny Cypress plugin
that helps you write and organize test setups. It's kind of like a namespaced cy.task()
with some
extra stuff.
Tasks are declared as "routines" per spec-file in so-called routines-files:
cypress/integration/login.spec.jslogin.routines.jssignup.spec.jssignup.routines.jsdashboard.spec.jsdashboard.routines.js
Routines files are just factory functions that return a JavaScript object with functions (routines) attached it:
cypress/integration/login.routines.js
module.exports = (db) => {return {createUser(user) {const result = await db.collection('users').insertOne(userData)return result},verifyEmailOfUser(userId) {const result = await db.collection('users').updateOne({ id: userId }, { $set: { emailVerified: true } })return result}}}
Routines are called from your spec-file with cy.routine()
, analogously to cy.task()
:
cypress/integration/login.spec.js
describe('Login', function () {it('redirects to the dashboard after login', function () {const userData = {name: "Max"email: 'max@maxschmitt.me'}cy.routine('createUser', userData).then((result) => {cy.visit('/login')cy.fillLoginForm(userData)cy.get('button[type="submit"]').click()cy.url().should('include', '/dashboard')})})})
Routines can only be called from their respective spec-file. So any routine defined in login.routines.js
can only be called
from login.spec.js
.
I've been using a private version of cypress-routines
for a few years now and it's been working
really well for projects with many spec-files and many more tests.
If you're interested in learning more, check out the cypress-routines docs.
Or have a look at the following screencast to see cypress-routines
in action.
Hi, I’m Max! I'm a fullstack JavaScript developer living in Berlin.
When I’m not working on one of my personal projects, writing blog posts or making YouTube videos, I help my clients bring their ideas to life as a freelance web developer.
If you need help on a project, please reach out and let's work together.
To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.