Skip to content

Instantly share code, notes, and snippets.

@MohannadNaj
Last active April 26, 2020 12:34
Show Gist options
  • Save MohannadNaj/06548671aba921f703c04cb542830048 to your computer and use it in GitHub Desktop.
Save MohannadNaj/06548671aba921f703c04cb542830048 to your computer and use it in GitHub Desktop.
PHPUnit watcher for Laravel Mix

PHPUnit watcher for Laravel Mix

I wrote this snippet to watch PHP files and run vendor/bin/phpunit on file changes.

Since chokidar is already installed on laravel-mix projects(it's one of mix dependencies), it's exactly the watcher we need, and we don't have to npm install anything more.

Steps:

1- On your laravel-mix root directory, create a new file called: phpunit-watcher.js:

	var files = ['src/**/*.php',
	            'tests/**/*.php',
	            'app/**/*.php'];

	var cmd = '"./vendor/bin/phpunit"';

	var chokidar = require('chokidar');

	let handleOutput = (error, stdout, stderr) => {
		    if (error) {
		        console.error(`exec error: ${error}`);
		    }
		    console.log(`${stdout}`);
		    console.log(`${stderr}`);
		};

	const exec = require('child_process').exec;

	var watcher = chokidar.watch(files);

	// Event listeners.
	watcher
	  .on('change', path => {
		exec(cmd, handleOutput);
	  });

2- require this file in your webpack.mix.js project:

let mix = require('laravel-mix');

// ....
// ....

require('./phpunit-watcher');

and that's it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment