Published: 03.12.2020 | Edited: 22.12.2020 | Tags: bash,cypress

Prevent push when skipping Cypress tests

Here's way I use to prevent pushing changes when some of the the Cypress tests are being skipped

  • Install required packages
npm i -D cypress husky start-server-and-test
  • Define your dev script in package.json if not done by your scaffolding
...
"scripts": {
+  "dev": "<start your server>"
}

Test by running and make sure your server started

npm run dev
  • Create the file cypress.json, modify the port if needed
{
  "baseUrl": "http://localhost:3000/"
}
  • Common Cypress run script
...
"scripts": {
  "dev": "<start your server>",
+ "cy:run": "cypress run"
}

Runing Cypress for the first time initializes it1

$ npm run cy:run
Can't run because no spec files were found.
We searched for any files inside of this folder:
/project-path/cypress/integration
  • Test script waits for dev and then does cy:run2
...
"scripts": {
  "dev": "<start your server>",
  "cy:run": "cypress run",
+ "test": "start-server-and-test dev http://localhost:3000 cy:run"
}

A start-test is a shorter alias and specifying port is sufficient3

...
"scripts": {
  "dev": "<start your server>",
  "cy:run": "cypress run",
- "test": "start-server-and-test dev http://localhost:3000 cy:run"
+ "test": "start-test dev 3000 cy:run"
}
  • Create the simplest test in cypress/integration/spec.js
/// <reference types="cypress" />
describe("Simplest test should", () => {
  it("visit base URL", () => {
    cy.visit("/")
  })
})

So far so good, just a quick sanity check

npm run test
  • Add a pre-push hook into package.json4
"scripts": {
  "dev": "<start your server>",
  "cy:run": "cypress run",
  "test": "start-test dev 3000 cy:run"
},
...
+"husky": {
+  "hooks": {
+    "pre-push": "npm run test"
+  }
}
  • Modify the spec.js to contain either .skip or .only Mocha modifier5
/// <reference types="cypress" />
describe("Simplest test should", () => {
  it.only("visit base URL", () => {
    cy.visit("/")
  })
})
  • Lastly, skipped tests detection before the tests6
...
"scripts": {
  "dev": "<start your server>",
  "cy:run": "cypress run",
  "test": "start-test dev 3000 cy:run"
},
"husky": {
  "hooks": {
-   "pre-push": "npm run test"
+   "pre-push": "grep -Rvzq -e '.skip' -e '.only' cypress/integration && npm run test"
  }
}

Done!

Sources are available in the repository

Further read

  1. https://github.com/cypress-io/cypress-skip-test
  2. https://medium.com/swlh/react-js-adding-eslint-with-prettier-husky-git-hook-480ad39e65e9
  3. https://github.com/lo1tuma/eslint-plugin-mocha/blob/master/docs/rules/no-skipped-tests.md
  4. https://www.cypress.io/blog/2017/05/30/cypress-and-immutable-deploys/
  5. https://github.com/cypress-io/eslint-plugin-cypress/issues/31#issuecomment-590037953

References