观察并重新运行 Jest JS 测试

开玩笑的文档建议使用 npm test来执行测试。

有没有一种方法可以监视源代码和测试,以便在相关文件被更改时自动重新运行 Jest 测试?

67959 次浏览
  1. install a couple of Grunt packages:

    npm install grunt-contrib-watch grunt-exec --save-dev
    
  2. 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');
    }
    
  3. then simply run:

    grunt watch
    

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

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
});

If you have npm test configured, you can just run npm test -- --watch.

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"

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:

  1. Install npm packege:

npm install --save-dev jest jest-watch-typeahead

  1. Add to jest.config.js next code:
module.exports = {
watchPlugins: [
'jest-watch-typeahead/filename',
'jest-watch-typeahead/testname',
],
};
  1. Run Jest in watch mode

yarn jest --watch

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