Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-run Cypress tests in GUI when webpack-dev-server causes page reload

I'm using webpack-dev-server and the Cypress GUI for a development workflow and I'd like for Cypress to automatically re-run/restart tests when the page reloads as triggered by WDS auto-reload.

What happens now is that I see WDS cause the page to reload, but the Cypress session just stays where it left off.

I can't seem to find a way to make this happen. I'm not seeing any public (or private, for that matter) way to trigger Cypress to re-run the currently selected test.

like image 632
Derek Harmel Avatar asked Oct 17 '22 13:10

Derek Harmel


1 Answers

UPDATE: Now there's an NPM package for this

cypress-hmr-restarter - it listens to the websocket that webpack-dev-server uses to reload the page

npm install --save-dev cypress-hmr-restarter

in cypress/support/index.js:

// cypress/support/index.js
import 'cypress-hmr-restarter'

see https://github.com/cypress-io/cypress/issues/456#issuecomment-566499738

Older hacky solution:

You can add the following to cypress/support/index.js (or at the top of a spec file):

Cypress.on('window:before:load', (win)=>{
  const _consoleInfo = win.console.info
  win.console.info = function () {
    if (arguments[0].includes('App updated.')) {
      cy.$$('.restart', top.document).click()
    }
    return _consoleInfo.apply(win.console, arguments)
  }
})

This will work as long as you have webpack-dev-server info being printed to the console (there are no other hooks into the webpack reloading behavior I could find)

The $('.restart').click() is a hilariously simple way to trigger a test re-run

Alternatively, you could try this plugin which sets up its own watchers on your source files, and re-runs your tests when changes are detected: https://github.com/bahmutov/cypress-watch-and-reload

like image 83
bkucera Avatar answered Nov 15 '22 04:11

bkucera