If you register multiple Cypress plugins using on(eventName, callback)
then Cypress v12.9.0 notifies only the last registered plugin when the event eventName
happens. Seems like this bug was introduced in Cypress v10 and described in the issue #22428. At first I put up with it, even if I use a log of my own plugins but lately is has really been annoying as I combine cypress-split and @bahmutov/cypress-code-coverage plugins. So I decided to write one more plugin to fix on(eventName, callback)
registration. I call my plugin cypress-on-fix and it is very easy to use in your projects.
Use
Just install the plugin as a dev dependency
1 | # install using NPM |
Proxy the on
argument in your cypress.config.js
file like this:
1 | const { defineConfig } = require('cypress') |
Boom, Cypress emits an event, the wrapper code in cypress-on-fix
receives it (single subscription) and then emits it to every listener subscribed to it (which can be multiple plugins). Why do I have to fix everything in this test runner?
Example
🎁 Find the simple example shown in this blog post in the repository bahmutov/cypress-on-fix-example.
Here is the cypress.config.js
showing a typical config. We can have multiple "plugins" that need to do something before the test run, after each spec, and after the run is finished.
1 | // cypress.config.js |
If you run this project, you will see only the last registered callback for every event:
1 | $ npx cypress run |
The previous callbacks were never called.
Now let's add the fix.
1 | $ npm i -D cypress-on-fix |
The new plugin should wrap the on
argument passed to the setupNodeEvents(on, config)
1 | // updated cypress.config.js |
To focus on the changed line:
1 | // 🚨 BEFORE |
Note: if you are doing component testing, you might have a separate setupNodeEvents(on, config)
and must use cypress-on-fix
there too.
Running the specs now correctly executes all event callbacks
1 | $ npx cypress run |
Note: if you are curious why multiple plugins need to listen to the same event, checkout what my plugins can do together in Testing The Swag Store course. The plugins work together to split all tests to run in parallel and then produce combined code coverage report all without using any dashboards, just by using GitHub Actions, or any CI really.
The @bahmutov/cypress-code-coverage merges code reports and even adds its own summary to the GHA output
Pretty neat, I will write a future blog post how it all works.