简体   繁体   中英

How to make mocha watch, compile and test coffeescript with dependencies on save

I'm working on a project that uses coffeescript for development and testing. I run the tests in node with mocha's --watch flag on so I can have the tests run automatically when I make changes.

While this works to some extent, only the ./test/test.*.coffee files are recompiled when something is saved. This is my directory structure:

/src/coffee
-- # Dev files go here
/test/
-- # Test files go here

The mocha watcher responds to file changes inside the /src and /test directories, but as long as only the files in the /test directory are recompiled continuous testing is kind of borked. If I quit and restart the watcher process the source files are also recompiled. How can I make mocha have the coffee compiler run over the development files listed as dependencies inside the test files on each run?

Here is my answer using grunt.js

You will have to install grunt and few additionnal packges.

npm install grunt grunt-contrib-coffee grunt-simple-mocha grunt-contrib-watch

And write this grunt.js file:

module.exports = function(grunt) {

  grunt.loadNpmTasks('grunt-contrib-coffee');
  grunt.loadNpmTasks('grunt-simple-mocha');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.initConfig({
    coffee:{
      dev:{
        files:{
          'src/*.js':'src/coffee/*.coffee',
        }
      },
      test:{
        files:{          
          'test/test.*.js':'test/test.*.coffee'
        }
      }
    },
    simplemocha:{
      dev:{
        src:"test/test.js",
        options:{
          reporter: 'spec',
          slow: 200,
          timeout: 1000
        }
      }
    },
    watch:{
      all:{
        files:['src/coffee/*', 'test/*.coffee'],
        tasks:['buildDev', 'buildTest', 'test']
      }
    }
  });

  grunt.registerTask('test', 'simplemocha:dev');
  grunt.registerTask('buildDev', 'coffee:dev');
  grunt.registerTask('buildTest', 'coffee:test');
  grunt.registerTask('watch', ['buildDev', 'buildTest', 'test', 'watch:all']);

};

Note: I didn't have some detials on how you build / run your tests so you certainly have to addapt ;)

Then run the grunt watch task :

$>grunt watch

Using a Cakefile with flour :

flour = require 'flour'
cp    = require 'child_process'

task 'build', ->
    bundle 'src/coffee/*.coffee', 'lib/project.js'

task 'watch', ->
    invoke 'build'
    watch 'src/coffee/', -> invoke 'build'

task 'test', ->
    invoke 'watch'
    cp.spawn 'mocha --watch', [], {stdio: 'inherit'}

Mocha already watches the test/ folder, so you only need to watch src/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM