Automatically running tests using TypeScript and Mocha when any file changes

606 Views Asked by At

I need to build a development environment which will automatically compile, run the tests and then TSLint when any .ts file in ./src/ or ./test/ changes, and print out the results of the tests and the lint.

./src/*.ts  --\   (tsc --watch)         (mocha --watch)
               |---------------> ./lib/ ---------------> console.log
./test/*.ts --/      |
                     |   (tslint --watch)
                     |--------------------> console.log

I've written npm scripts to run this work flow only once with npm run test:

// package.json
{
  "scripts": {
    "pretest": "tsc", // will compile *.ts in src/ and test/ to lib/
    "test": "mocha --reporter spec --full-trace lib/test/tests.js",  // run the compiled test file
    "posttest": "gulp tslint"  // run gulp for tslint
  }
}

I wrote a gulp task to watch file changes to trigger the npm script:

// gulpfile.js
var exec = require('gulp-exec');
gulp.task("watch", () => {
  gulp.watch(paths.scripts, () => {
    exec(`npm run test`, {
      continueOnError: true,
      pipeStdout: true
    })
  });
});

I ran gulp watch, but I didn't show the results of test and lint in the console.

How to achieve my goal that it will run ts-compile, mocha-test, and then ts-lint when any *.ts file changes?

1

There are 1 best solutions below

0
On

It would be easier to your tests directly in mocha, you would then have more granular control on your various tasks.

You could have the following tasks:

gulp.task('compileSrcForWatch', ['compileSrc'], () => gulp.start('test'));
gulp.task('compileTestForWatch', ['compileTest'], () => gulp.start('test'));

gulp.task('watchAndTest', () => {
    gulp.watch(config.inputSourceFiles, ['compileSrcForWatch']);
    gulp.watch(config.inputTestFiles, ['compileTestForWatch']);
});

I've created a gist with the whole file here.