Cypress browser auto reloading in real time is not working

Viewed 1131

As the title says, I have to use the Cypress Test Runner to see the results every time I change my code. But as per the instructions, it should be auto-reloading and showing the results in real-time.

OS: Windows 10 Chrome: Version 78.0.3904.70

1 Answers

Here are two solutions, based on whether you have a build step, or not.

  1. If you don't have a build step, then it's rather easy:

    In your cypress/plugins/index.js:

    1. Obtain file handles of spec files that are currently running, so that you can emit rerun event on them.
    2. Set up a chokidar (or similar) watcher, listen on your file changes, and rerun the spec.

      // (1) setup to obtain file handles 
      // ------------------------------------------------------
      
      let openFiles = [];
      
      module.exports = ( on ) => {
          on('file:preprocessor', file => {
              if (
                  /\.spec\.js/.test(file.filePath) &&
                  !openFiles.find(f => f.filePath === file.filePath)
              ) {
      
                  openFiles.push(file);
      
                  file.on('close', () => {
                      openFiles = openFiles.filter(f => f.filePath !== file.filePath);
                  });
              }
      
              // tells cypress to not compile the file. If you normally
              //  compile your spec or support files, then instead of this line,
              //  return whatever you do for compilation
              return file.filePath;
          });
      
          on('before:browser:launch', () => {
              openFiles = [];
          });
      };
      
      // (2) watching and re-running logic
      // ------------------------------------------------------
      
      chokidar.watch([ /* paths/to/watch */ ])
          .on( "change", () => rerunTests());
      
      function rerunTests () {        
          // https://github.com/cypress-io/cypress/issues/3614
          const file = openFiles[0];
          if ( file ) file.emit('rerun');
      }
      
  2. If you have a build step, the workflow is more involved. I won't get into implementation details, but just to get an overview:

    1. Set up an IPC channel when you start your build-step watcher, and upon file save & compilation, emit a did-compile event or similar.
    2. The logic in cypress/plugins/index.js mostly remains the same as in previous solution, but instead of a chokidar watcher, you'll subscribe on the IPC server's did-compile event, and rerun the specs when the event is emitted.

For more info, refer to Preprocessors API, and cypress-io/cypress-watch-preprocessor.

Related