
Pick Tests By Network Calls
How do you pick the tests to run? Do you run the changed specs first? Run tests that visit a particular page? Pick tests using test tags? This blog post will show yet another way of picking end-to-end Cypress tests to execute: by the network calls the tests make.
We can track the network calls each test makes using the super-powerful and awesome cy.intercept command:
1 | beforeEach(function () { |
We can see the intercepted network calls in the DevTools console
We need to store these API calls somewhere. If you are using my plugin cypress-visited-urls it exposes a static method Cypress.addVisitedTestEvent
that you can use to send custom events. The plugin stores these events and even keeps track of the event counts for each test.
1 | beforeEach(function () { |
🎁 You can find the complete source code shown in this blog post in the branch blog-post of the repo bahmutov/called-urls-examples.
Super, so if we run this test even once, it will save a JSON file
1 | { |
You should commit this file with your source code update it periodically when running the tests on CI.
Finding the specs
Next, we need to define a Node script to find the specs by a network call. For example, we want to find all specs that delete items.
1 | #!/usr/bin/env node |
Let's find the specs with tests where the application makes the network call DELETE /todos
1 | $ node ./bin/find-specs.js --method DELETE --path /todos |
So there are two specs that have tests that exercise the "delete item" feature. Let's see how many such calls the tests make
1 | $ node ./bin/find-specs.js --method DELETE --path /todos --output table |
So during delete.cy.js
spec execution the app deletes 4 different items, and that is why this spec filename is shown first. We can feed this list directly into Cypress "run" command
1 | $ npx cypress run --spec $(node ./bin/find-specs.js --method DELETE --path /todos) |
Beautiful.