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?
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
grunt watch
will not, it will continue the current test-run ignoring changes that occur while the tests are running.
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"
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
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
});
__tests__
folder it does not work with this jestConfig
. After reading the docs and playing a bit this works for me: var jestConfig = { rootDir: "__tests__" }
Mar 29, 2016 at 15:30
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
If you want to run a single file in watch mode:
yarn run test --watch FileName.test.jsx
I personally use the npm package jest-watch-typeahead.
You need to do 3 steps:
npm install --save-dev jest jest-watch-typeahead
module.exports = { watchPlugins: [ 'jest-watch-typeahead/filename', 'jest-watch-typeahead/testname', ], };
yarn jest --watch
npm t
The shortest way to rerun tests and turn on watch mode in jest.
yarn t