mishelen
2/10/2015 - 12:10 PM

A hackish way to re-run tests just for the changed file. (Gulp + Jest)

A hackish way to re-run tests just for the changed file. (Gulp + Jest)

// ... requires, initialization and stuff ...

function runJest(changedFilePath) {
	var nodeModules = path.resolve('./node_modules');
	var jestConfig = {
		scriptPreprocessor: nodeModules + '/gulp-jest/preprocessor.js',
		unmockedModulePathPatterns: [nodeModules + '/react'],
		moduleFileExtensions: ['js', 'jsx'],
		testFileExtensions: ['js', 'jsx'],
	};
	if (changedFilePath) {
		// changedFilePath should be '/full/path/to/component.jsx' or '/path/to/component-test.jsx'
		var changedFileBaseName = changedFilePath.match(/(.*\/)?([A-Za-z0-9]*)(-test)?\.jsx/)[2];
		// and making it a regex that matches all the files except this one
		jestConfig.testPathIgnorePatterns = 
			['^(.*\/)?(?!' + changedFileBaseName + ')[A-Za-z0-9]*-test.*$'];

		// HINT: use http://regexr.com/ if you ever need to debug the above regular expressions
	}
	return gulp.src('app/scripts/**/__tests__')
		.pipe($.jest(jestConfig));

}

gulp.task('jest', function() {
	runJest(); // Run all tests.
});

// ... other tasks ...

// Watch
gulp.task('watch', ['html', 'bundle', 'serve'], function() {

	// Watch all kinds of stuff...
	// ....

	// Re-run the unit tests when js changes
	gulp.watch(['app/scripts/**/*'], function(fileChanged) {
		runJest(fileChanged.path);
	});
});

// ...other tasks...