Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 838
Kevin Avatar asked Mar 10 '14 02:03

Kevin


People also ask

What is mocha chai?

Mocha is a JavaScript test framework running on Node. js and in the browser. Mocha allows asynchronous testing, test coverage reports, and use of any assertion library. Chai is a BDD / TDD assertion library for NodeJS and the browser that can be delightfully paired with any javascript testing framework.

What is unit testing in node JS?

NodeJS Unit testing is the method of testing small pieces of code/components in isolation in your NodeJS application. This helps in improving the code quality and helps in finding bugs early on in the development life cycle.


1 Answers

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?

like image 198
Azerothian Avatar answered Sep 30 '22 08:09

Azerothian