Watch and rerun Jest JS tests
NpmJestjsNpm Problem Overview
The Jest documentation suggests using npm test
to execute tests.
Is there a way of watching your source and tests to rerun Jest tests automatically when relevant files have been changed?
Npm Solutions
Solution 1 - Npm
Thanks to Erin Stanfill for pointing out, Jest already has support for automatically re-running. The better configuration for package.json
would be
{
"scripts": {
"test": "jest"
}
}
To turn on the watch mode, just use
$ npm run test -- --watch
Or
$ yarn run test --watch
Solution 2 - Npm
If you have npm test
configured, you can just run npm test -- --watch
.
Solution 3 - Npm
Start you tests in watch mode.
jest --watch fileName.test.js
As per documentation
Run tests that match this spec name (match against the name in describe
or test
, basically).
jest -t name-of-spec
// or in watch mode
jest --watch -t="TestName"
Solution 4 - Npm
-
install a couple of Grunt packages:
npm install grunt-contrib-watch grunt-exec --save-dev
-
make a
Gruntfile.js
with the following:module.exports = function(grunt) { grunt.initConfig({ exec: { jest: 'node node_modules/jest-cli/bin/jest' }, watch: { files: ['**/*.js'], tasks: ['exec:jest'] } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-exec'); }
-
then simply run:
grunt watch
Solution 5 - Npm
This example shows how to use gulp to run your Jest tests using jest-cli
, as well as a tdd
gulp task to watch files and rerun Jest tests when a file changes:
var gulp = require('gulp');
var jest = require('jest-cli');
var jestConfig = {
rootDir: 'source'
};
gulp.task('test', function(done) {
jest.runCLI({ config : jestConfig }, ".", function() {
done();
});
});
gulp.task('tdd', function(done) {
gulp.watch([ jestConfig.rootDir + "/**/*.js" ], [ 'test' ]);
});
gulp.task('default', function() {
// place code for your default task here
});
Solution 6 - Npm
As a complement suggestion you can add "--watchAll" into your package.json file like this:
"scripts": {
"test": "jest --watchAll"
},
Each time you run npm test, the watch mode will be enable by default.
For more info npm CLI docs
Solution 7 - Npm
If you want to run a single file in watch mode:
yarn run test --watch FileName.test.jsx
Solution 8 - Npm
I personally use the npm package jest-watch-typeahead.
You need to do 3 steps:
- Install npm packege:
> npm install --save-dev jest jest-watch-typeahead
- Add to jest.config.js next code:
> module.exports = { > watchPlugins: [ > 'jest-watch-typeahead/filename', > 'jest-watch-typeahead/testname', > ], > };
- Run Jest in watch mode
> yarn jest --watch