Skip to content

🚀 Feature [watch mode]: begin running tests immediately instead of waiting for watcher ready event #5372

@jedwards1211

Description

@jedwards1211

Feature Request Checklist

Overview

In my large project with thousands of files, mocha watch mode takes many seconds longer to start the first test run than non-watch mode, unnecessarily wasting time. I wish it would start running the tests immediately instead of waiting for the watcher to be ready.

Suggested Solution

To run immediately but still be able to rerun on a file change, we just need to turn off ignoreInitial and distinguish between initial 'add' events and paths added after test startup. We can compare the mtime of the path to the test startup time to decide if the change should trigger a rerun.

I am ready to make a PR for this, the change to createWatcher looks like:

  const watcher = chokidar.watch('.');

  const rerunner = createRerunner(mocha, watcher, {
    beforeRun
  });

  const startTime = new Date();
  let ready = false;
  watcher.on('ready', () => {
    ready = true;
  });

  watcher.on('all', async function handleEvent(event, filePath, stat) {
    if (exiting) return;
    if (event === 'unlink' || (stat ? stat.mtime > startTime : ready)) {
      if (event === 'add') {
        tracker.regenerate();
      }
      if (tracker.has(filePath)) {
        rerunner.scheduleRun();
      }
      return;
    }
    if (!ready && !stat) {
      fs.stat(filePath, (err, stat) => {
        if (stat) handleEvent(event, filePath, stat);
      });
    }
  });

  (async () => {
    if (!globalFixtureContext) {
      debug('triggering global setup');
      try {
        globalFixtureContext = await mocha.runGlobalSetup();
      } catch (err) {
        console.error(err);
      }
    }
    rerunner.run();
  })();

Alternatives

Right now I'm pnpm patching mocha in my projects that have this issue.

Additional Info

No response

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions