Kevin
Kevin

Reputation: 2154

Gulp, Mocha, Watch Not Reloading My Source Files

I am attempting to get gulp working to help automate some unit testing. I have the following gulp file.

var gulp = require('gulp'),
    mocha = require('gulp-mocha');

gulp.task('unit', function() {
    return gulp.src('test/unit/**/*.js')
        .pipe(mocha({ reporter: 'spec' }))
        .on('error', handleError);
});

gulp.task('watch', function() {
    gulp.watch(['src/**/*.js', 'test/unit/**/*.js'], ['unit']);
});

gulp.task('test', ['unit', 'watch']);

When I run 'gulp unit', the tests run fine.

When I run 'gulp test', the tests run, and it appears that 'watch' is working. If I make a change to one of the test files, the tests rerun correctly, taking into account the changes I made in the test file.

If I make changes to my source files, the tests also re-run, but they DO NOT run against the updated version of the source file.

My thought is that somehow, the source file is being cached, but I cannot find any others who seem to have had this issue or find a solution.

Thanks for helping this Gulp/Node/Mocha newbie!

Upvotes: 14

Views: 2817

Answers (2)

j03m
j03m

Reputation: 5303

I didn't want to mod all my tests so I just jammed this function right before I start piping test files to mocha:

function freshFiles(chunk, enc, cb){
    _.forOwn(require.cache, function(value, key){
        if (key.indexOf('lib') !== -1 && key.indexOf('node_modules')===-1){
            delete require.cache[key];
        }
    });
}

This targets my lib folder but nothing in the node_modules path.

In gulp it looks like:

gulp.task('test', function () {
    var mocha = require("gulp-mocha");
    freshFiles();
    gulp.src(testSources)
        .pipe(mocha({ reporter: 'spec', growl: 'true' }))
        .on('error', gutil.log);

});

Upvotes: 1

Azerothian
Azerothian

Reputation: 386

I had the same issue but i found a fix,

The issue is that require in nodejs is caching your src files when you are running your tests via watch

I used the following function in my test file to invalidate the cache of the src file, in replace of require.

Apparently doing this can be dangerous, please see the link at the bottom of my post for more information. Development use only ;)

Coffeescript - module-test.coffee

nocache = (module) ->
    delete require.cache[require.resolve(module)]
    return require(module)

Module = nocache("../module")
describe "Module Test Suite", () ->
    newModule = new Module();
    ...

Javascript - module-test.js

var Module, nocache;
nocache = function(module) {
    delete require.cache[require.resolve(module)];
    return require(module);
};
Module = nocache("../src/module");

describe("Module Test Suite", function () {
    newModule = new Module();
    ...

see here for more information: node.js require() cache - possible to invalidate?

Upvotes: 7

Related Questions