GithubHelp home page GithubHelp logo

grunt-mocha-test's Introduction

grunt-mocha-test

Build Status Coverage Status

A grunt task for running server side mocha tests

Usage

Install next to your project's Gruntfile.js with:

npm install grunt-mocha-test --save-dev

Running tests

Here is a simple example gruntfile if you just want to run tests

module.exports = function(grunt) {

  // Add the grunt-mocha-test tasks.
  grunt.loadNpmTasks('grunt-mocha-test');

  grunt.initConfig({
    // Configure a mochaTest task
    mochaTest: {
      test: {
        options: {
          reporter: 'spec',
          captureFile: 'results.txt', // Optionally capture the reporter output to a file
          quiet: false, // Optionally suppress output to standard out (defaults to false)
          clearRequireCache: false, // Optionally clear the require cache before running tests (defaults to false)
          clearCacheFilter: (key) => true, // Optionally defines which files should keep in cache
          noFail: false // Optionally set to not fail on failed tests (will still fail on other errors)
        },
        src: ['test/**/*.js']
      }
    }
  });

  grunt.registerTask('default', 'mochaTest');

};

Options

The following options are specific to grunt-mocha-test (ie. not mocha options)

  • captureFile - specify a file to capture all output to (will include any output from console.log)
  • quiet - true to not output anything to console (normally used with the captureFile option when console output would not be human readable)
  • clearRequireCache - true to clear the require cache before each test run (normally used with watch when not spawning each test run in a new nodejs context)
  • clearCacheFilter - function() { return true/false } to say which files should remain in cache. Only works with clearRequireCache set to true)
  • noFail - true to prevent the task failing on failed tests. Useful for CI setups where test reports are processed separately. Will still fail on other errors

The following mocha options have also been tested (others may have been added since the time of writing through changes to mocha)

  • grep
  • ui
  • reporter
  • timeout
  • invert
  • ignoreLeaks
  • growl
  • globals
  • bail
  • require
  • slow

Specifying compilers

The Mocha --compilers option is almost identical to the --require option but with additional functionality for use with the Mocha --watch mode. As the --watch mode is not relevant for this plugin there is no need to implement a separate compilers option and actually the require option should be used instead.

The following example shows the use of the CoffeeScript compiler.

npm install coffee-script
mochaTest: {
  test: {
    options: {
      reporter: 'spec',
      require: 'coffee-script/register'
    },
    src: ['test/**/*.coffee']
  }
}

This is an example for the Babel 6 compiler (babel must be configured separately if you want to use it for something like ES6/ES2015).

npm install babel-register
mochaTest: {
  test: {
    options: {
      reporter: 'spec',
      require: 'babel-register'
    },
    src: ['test/**/*.js']
  }
}

In order to make this more user friendly, the require option can take either a single file/function or an array of files/functions in case you have other globals you wish to require.

eg.

mochaTest: {
  test: {
    options: {
      reporter: 'spec',
      require: [
        'coffee-script/register',
        './globals.js',
        function(){ testVar1=require('./stuff'); },
        function(){ testVar2='other-stuff'; }
      ]
    },
    src: ['test/**/*.coffee']
  }
}

NB. File references for the require option can only be used with Javascript files, ie. it is not possible to specify a ./globals.coffee in the above example.

Specifying a Mocha module

grunt-mocha-test uses npm's peerDependency functionality and thus uses whatever version of mocha is installed in your project. If your project does not have mocha installed, a compatible version will automatically be installed when adding grunt-mocha-test.

Generating coverage reports

Here is an example gruntfile that registers 2 test tasks, 1 to run the tests and 1 to generate a coverage report using blanket.js to instrument the javascript on the fly.

npm install blanket
module.exports = function(grunt) {

  grunt.loadNpmTasks('grunt-mocha-test');

  grunt.initConfig({
    mochaTest: {
      test: {
        options: {
          reporter: 'spec',
          // Require blanket wrapper here to instrument other required
          // files on the fly. 
          //
          // NB. We cannot require blanket directly as it
          // detects that we are not running mocha cli and loads differently.
          //
          // NNB. As mocha is 'clever' enough to only run the tests once for
          // each file the following coverage task does not actually run any
          // tests which is why the coverage instrumentation has to be done here
          require: 'coverage/blanket'
        },
        src: ['test/**/*.js']
      },
      coverage: {
        options: {
          reporter: 'html-cov',
          // use the quiet flag to suppress the mocha console output
          quiet: true,
          // specify a destination file to capture the mocha
          // output (the quiet option does not suppress this)
          captureFile: 'coverage.html'
        },
        src: ['test/**/*.js']
      }
    }
  });

  grunt.registerTask('default', 'mochaTest');
};

As noted above it is necessary to wrap the blanket require when calling mocha programatically so coverage/blanket.js should look something like this.

var path = require('path');
var srcDir = path.join(__dirname, '..', 'src');

require('blanket')({
  // Only files that match the pattern will be instrumented
  pattern: srcDir
});

This will preprocess all .js files in the src directory. Note that Blanket just uses pattern matching so this rework of the paths prevents files in node_modules being instrumented too. Also bear in mind using Blanket to instrument files on the fly only works if the file is not already in the require cache (this is an odd case but if you can't figure out why a file is not instrumented and the pattern looks ok then this may be the cause).

Failing tests if a coverage threshold is not reached

Building on the previous example, if you wish to have your tests fail if it falls below a certain coverage threshold then I advise using the travis-cov reporter

npm install travis-cov
module.exports = function(grunt) {

  grunt.loadNpmTasks('grunt-mocha-test');

  grunt.initConfig({
    mochaTest: {
      test: {
        options: {
          reporter: 'spec',
          require: 'coverage/blanket'
        },
        src: ['test/**/*.js']
      },
      'html-cov': {
        options: {
          reporter: 'html-cov',
          quiet: true,
          captureFile: 'coverage.html'
        },
        src: ['test/**/*.js']
      },
      // The travis-cov reporter will fail the tests if the
      // coverage falls below the threshold configured in package.json
      'travis-cov': {
        options: {
          reporter: 'travis-cov'
        },
        src: ['test/**/*.js']
      }
    }
  });

  grunt.registerTask('default', 'mochaTest');
};

Don't forget to update package.json with options for travis-cov, for example:

  ...

  "config": {
    "travis-cov": {
      // Yes, I like to set the coverage threshold to 100% ;)
      "threshold": 100
    }
  },

  ...

Instrumenting source files with coverage data before running tests

In most cases it may be more useful to instrument files before running tests. This has the added advantage of creating intermediate files that will match the line numbers reported in exception reports. Here is one possible Gruntfile.js that uses the grunt-blanket plug in.

npm install grunt-contrib-clean
npm install grunt-contrib-copy
npm install grunt-blanket
npm install travis-cov
module.exports = function(grunt) {

  grunt.loadNpmTasks('grunt-mocha-test');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-blanket');

  grunt.initConfig({
    clean: {
      coverage: {
        src: ['coverage/']
      }
    },
    copy: {
      coverage: {
        src: ['test/**'],
        dest: 'coverage/'
      }
    },
    blanket: {
      coverage: {
        src: ['src/'],
        dest: 'coverage/src/'
      }
    },
    mochaTest: {
      test: {
        options: {
          reporter: 'spec',
        },
        src: ['/coverage/test/**/*.js']
      },
      coverage: {
        options: {
          reporter: 'html-cov',
          quiet: true,
          captureFile: 'coverage.html'
        },
        src: ['/coverage/test/**/*.js']
      },
      'travis-cov': {
        options: {
          reporter: 'travis-cov'
        },
        src: ['/coverage/test/**/*.js']
      }
    }
  });

  grunt.registerTask('default', ['clean', 'blanket', 'copy', 'mochaTest']);
};

This will delete any previously instrumented files, copy the test files to a coverage folder and instrument the src javascript files to the coverage folder. Lastly it runs tests from the coverage folder. It's more complicated but often easier to work with.

Running in permanent environments (like watch)

If you run grunt-mocha-test with grunt-contrib-watch using the spawn: false option, you will notice that the tests only run on the first change. Subsequent changes will result in an empty report with a 0 passing message.

This happens because mocha loads your tests using require resulting in them being added to the require cache. Thus once they have been loaded in a process the subsequent calls to require hit the cache without executing the code again. To prevent this from happening, use the clearRequireCache option (default value is false).

Here is an example that also demonstrates how to only run changed tests:

module.exports = function(grunt) {

  grunt.loadNpmTasks('grunt-mocha-test');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.initConfig({
    mochaTest: {
      test: {
        options: {
          reporter: 'spec',
          clearRequireCache: true
        },
        src: ['test/**/*.js']
      },
    },

    watch: {
      js: {
        options: {
          spawn: false,
        },
        files: '**/*.js',
        tasks: ['default']
      }
    }
  });

  // On watch events, if the changed file is a test file then configure mochaTest to only
  // run the tests from that file. Otherwise run all the tests
  var defaultTestSrc = grunt.config('mochaTest.test.src');
  grunt.event.on('watch', function(action, filepath) {
    grunt.config('mochaTest.test.src', defaultTestSrc);
    if (filepath.match('test/')) {
      grunt.config('mochaTest.test.src', filepath);
    }
  });

  grunt.registerTask('default', 'mochaTest');
};

Using node flags

There are some flags that Mocha supports that are actually Node flags, eg.

  • --debug
  • --harmony-generators

It is currently not possible to set these at runtime when using Mocha as a library and as such cannot be supported by grunt-mocha-test without a major refactor (and severe impact on performance as it would involve spawning processes).

The recommended way of using these flags would be to pass them to node when starting the grunt process. The simplest way to do this would be to leverage the scripts functionality of NPM and package.json.

  ...
  },
  "scripts": {
    "test": "node --debug --harmony-generators ./node_modules/.bin/grunt test"
  }
  ...

The tests would then be run using

npm test

Note that this assumes that grunt-cli has been installed locally and not globally

Contributing

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using:

npm test

License

Copyright © 2016 Peter Halliday
Licensed under the MIT license.

Donate Bitcoins

17LtnRG4WxRLYBWzrBoEKP3F7fZx8vcAsK

grunt-mocha-test's People

Contributors

arthurschreiber avatar clmsnskr avatar constellation avatar demmer avatar dy-dx avatar eclifford avatar egdelwonk avatar frekw avatar homeyer avatar ianwremmel avatar it-ony avatar itaylor avatar jamiebuilds avatar jugglinmike avatar ladnovsasha avatar larshassler avatar miktam avatar pdehaan avatar pghalliday avatar polarblau avatar shinnn avatar sirbrillig avatar stevenvachon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

grunt-mocha-test's Issues

Allow for compilers to be specified

Running the mocha command it's possible to specify specific compilers. It would be nice if we could specify a compiler from within the gruntfile as well.

From the mocha docs:

--compilers

coffee-script is no longer supported out of the box. CS and similar
transpilers may be used by mapping the file extensions (for use
with --watch) and the module name. For example --compilers 
coffee:coffee-script.

Setting working directory

My tests need to be run from a different working directory than the one where my Gruntfile resides. Is there a way to run mocha through this plugin with a different working directory?

mocha-test + watch only runs once

I've set up my gruntfile to use grunt-contrib-watch and launch mocha-test when it detects changes in my files.

The first time I change a file, it runs the test as it should. If I save the file again, however, all I get is "0 passing (0ms)".

Is there some sort of internal state preventing it from being run on the same files again? And if so, is there any way to fix this?

Share src property to all target?

Most of the time when using mochaTest:test and mochaTest:coverage (even travis one) the src prop points to the same location.

It would be nice if we could define the option at the task level as a default value for all targets.

Problem about the path of test files

If I cd in the folder where is the js file containing the test, and I execute mocha in this folder, the test will success.

If I execute grunt-mocha-test with grunt, the test fails.
I think the problem is related to the path.
I don't want to move the files containing test cases.

How may I solve this issue?

Assertion failure in async tests crashes grunt with Fatal error

I have some async tests in mocha (using BDD pattern and either expect.js or chai's expect) that crash grunt-mocha-test with a Fatal error. It happens in multiple reporter (list, spec and my own).

It is reproducible when you use the done parameter in an asynchronous scenario that has a failing assert in the callback. I tested using a setTimeout, process.nextTick and fs.readFile).

Command-line mocha reports/logs the failure as expected and finishes the suites properly but in grunt a Fatal error will show (in red) and make grunt exit hard:

Fatal error: expected true to equal false�

I see a similar issue here: yaymukund/grunt-simple-mocha#16, it seems grunt is overly aggressive in handling uncaughtException.

Singleton created in 'require:' option is not available, but works via mocha.opts

First, thanks for grunt-mocha-test-- we use it daily and appreciate the effort that's gone into it.

In our test suite we are currently using 'require' mocha.opts to load a file which populates a singleton, which all the tests can then then access.

However, when add the equivalent to our Gruntfile, it doesn't work:

require: './test/lib/bootstrap.js',

By adding a "console.log" statement to our bootstrap file, I can confirm that Grunt is actually finding and loading the file, but the singleton created by that file is not available to other tests as before.

I read in another issue that the implementation of 'require' is "simulated". Could this behavior difference be a side effect one of the differences?

Thanks!

Test coverage value in grunt task

Is there a way to have the overall coverage value reported to the grunt task so that rather than looking like this:

Running "mochaTest:coverage" (mochaTest) task

Done, without errors.

It would look like this:

Running "mochaTest:coverage" (mochaTest) task
    93% Overall Coverage
Done, without errors.

Or even better, pass / fail based on threshold and allow the threshold to be set within the gruntfile rather than via travis-cov.

Running "mochaTest:coverage" (mochaTest) task
    73% Overall Coverage: failed

Warning: Task "coverage" failed. Use --force to continue.

Aborted due to warnings.

Support grunt standard dynamic file selector

It looks like this is not supported:

http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically

I have a bunch of tests in a nested folder I want to run in a specific order so I have to specify them manually (instead of globbing). But it get tedious to specify the sub folder every time so I wanted to use the expand and cwd grunt options but when I do so only the first spec file gets executed.

I tried to fix this myself and made a test here but I can't run it as per #19.

When mocha-test part of task sequence , tasks after mocha-test were not executed

Hello
I have following question :
I defined some alias grunt task as following :

grunt.registerTask('new_task', ['mocha-test', 'other_task']);

When I execute this new defined task with command line grunt new_task , only mocha-test task executed , other_task were not started

In the case when I define reverse order as following

grunt.registerTask('new_reverse_task', ['other_task','mocha-test']);
both tasks executed

What can cause to the issue ? How can be caused to that both of tasks in the first case new_task will be executed ? Your help will be valuable . Thanks in advance

Support other mocha args

Like --harmony-generators or --debug
This is for upcoming node 0.11 which supports generator function. Also for emerging koa framework which make heavy use of generator. It'll be very helpful if we can do test from grunt-mocha-test with that, instead of cli command.

Support for compilers ?

Would it be possible eventually support --compilers switch for Mocha ? I am using CoffeeScript and without this I have to utilize grunt-contrib-coffee just for tests.

I tried to make it by myself, but got kinda lost in source code :)

Is there a benefit of having a seperated config task?

I was wondering why there is both a mochaTest main task as well as a mochaTestConfig options-task, most grunt plugins don't do this but have the options inside the tasks targets as per convention.

Does this provide a benefit that would negate managing the duplicate multi-task names?

Environment variables not honored?

I noticed that grunt-env does not work with the grunt-mocha-test plugin. It would be nice to use environment variables in a way that is compatible with grunt env so we can set the environment in Gruntfile.js.

watch doesn't react to changes if run after mochaTest

If I have the following definition:

grunt.registerTask('serve', [
    'mochaTest',
    'watch',
]);

where watch is defined by the grunt-contrib-watch package, then running grunt serve gives me:

grunth serve                                                                                                      24.03 21:08:02
Running "mochaTest:all" (mochaTest) task
  # some mocha output
  2 passing (29ms)


Running "watch" task
Waiting...

and gets stuck in the waiting phase, not reacting to file changes. If I change the definition to:

grunt.registerTask('serve', [
    'watch',
]);

it starts reacting for changes. I have a section in the watch config:

watch: {
    mochaTest: {
        files: ['<%= jshint.all.src %>'],
        tasks: ['mochaTest'],
    },
    /* ... */
},

and it works fine. The only case where it fails is if I additionally have the mochaTest task run before watch.

I also get other errors. In my configuration I actually have more tasks, the full definition of the relevant part is:

grunt.registerTask('lint', [
    'jshint',
    'jscs',
    'jsonlint',
]);

grunt.registerTask('test', [
    'checkDependencies',
    'merge-conflict',
    'lint',
    'mochaTest',
]);

grunt.registerTask('serve', [
    'test',
    'watch',
]);

if I move the mochaTest task above lint, I get errors in the lint task - the jshint task gets no files:

Running "jshint:all" (jshint) task
>> 0 files linted. Please check your ignored files.

the jscs task doesn't see my custom rules defined in a separate package jscs-trailing-comma... Whatever mochaTest does, it breaks following tasks.

Tested on grunt 0.4.4, all dependencies except jshint in newest versions, grunt-contrib-jshint 0.7.2.

EDIT: Setting clearRequireCache to true doesn't help.

EDIT 2: I've tried with 0.8.2, 0.9.4 & 0.10.0 and I have the same problem in all of them.

How do I write the output of tests to a file?

I am trying to output the results of my tests to a file but it's not working.

Here's a snip of my config:

'mytests': {
options: {
reporter: 'tap'
},
src: ['test/*/.js'],
dest: './tests.tap'
//tried output and captureFile
}
}

What is the correct way to redirect output to a file?

Configure more than 1 reporter

Hi!
I'd like to have test results in spec ( with coverage ) and in xunit ( without coverage ) format.
Could you please explain how to configure a grunt task for that?

grunt-mocha-tes is not in the npm registry

Trying to install and getting:

npm http GET https://registry.npmjs.org/grunt-mocha-test%3A%40~0.2.2
npm http 304 https://registry.npmjs.org/grunt-contrib-jshint
npm http 304 https://registry.npmjs.org/grunt
npm http 304 https://registry.npmjs.org/grunt-contrib-yuidoc
npm http 404 https://registry.npmjs.org/grunt-mocha-test%3A%40~0.2.2
npm ERR! 404 'grunt-mocha-test%3A%40~0.2.2' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, or http url, or git url.

Keep going when a test fails

When I run a suite of tests from the mocha command line it will continue with other tests and give a complete report of all failures at the end. grunt-mocha-test appears to stop at the first failure. Is there a way to make it continue?

Thanks!
Randy

Nested Grunt configuration blocks do not work

When I configure grunt-mocha-test using

mochaTest: {
  foo: {
    options: [  ],
    src: [  ]
  }
}

everything works fine. Especially, I am able to run it by calling:

$ grunt mochaTest:foo

If I now start to nest things, it doesn't work any more. E.g., if I use

mochaTest: {
  foo: {
    bar: {
      options: [  ],
      src: [  ]
    }
  }
}

and try to run it using

$ grunt mochaTest:foo:bar

it does not work. It basically looks as if there were no tests defined. If you run Grunt in --verbose mode you see that it only looks for mochaTest.foo, and does not dive down into recursion.

Is this by design, or is this a bug? Either way: How could I accomplish this?

Print stack traces when tests fail

When a test fails grunt quits with a simple error message. When I run the same test with mocha from the command line it gives me a stack trace. Is there a way to get stack traces from this plugin?

Thanks for your contributions to open source!
Randy

Grunt task for mocha-test fails if any tests fail.

Is it possible via an option or thru a patch to allow grunt to not fail if any tests fail. The reason for something like this would be to integrate more smoothly with CI systems like Jenkins.

As it is now, if any tests fail, the grunt task fails, so systems like Jenkins flag the build as failed regardless of how many tests fail or not. In some cases it may be useful to have a build only flagged as failing is a certain threshold of tests fail configurable by your CI (e.g. a development build / instance you are okay with having a few tests fail now and then). For this to happen, the grunt task would have to not exit with an error status code.

Here is the task setup I'm working with now

  mochaTest: {
      report: {
        options: {
          reporter: 'xunit',
          quiet: false,
          timeout: 50000
        },
        src: ['test/**/*_test.js'],
        dest: 'test/mochareport.xml'
      }
  },

Task for test coverage

What is the best way to implement task for test coverge

I can do following: grunt.js

And run it as grunt > cov.html.

Is there a better way to do it?

separate config for grunt tasks?

Is there a way to set a separate config for different tasks? For example, when running locally, I want ui: 'bdd', reporter: 'spec', but running in jenkins I just want: reporter: 'tap'

Also, is there a way to engage the mocha check-leaks feature via mochaTestConfig? I tried options: { ignoreLeaks: false } and tried to create some global variables in the tests, but it does not seem to be working.

How to tell grunt-mocha-test to use the mocha.opts file from the test folder?

In mocha you can use a file called mocha.opts to provide cli arguments to the mocha process. This file needs to be in the test folder.

Anyway, if I simply put

grunt.initConfig({
  mochaTest: {
    files: ['test/**/*.js']
  }
});

into my Gruntfile.js, mocha complains about suite not being defined, although the file mocha.opts exists and contains the line:

--ui tdd

Any ideas on how to solve this?

It looks as if mocha, if run by grunt-mocha-test, does not load this file at all.

require: chai not working

I am trying to use chai in my tests. Here is my configuration:

mochaTest: {
    test: {
        options: {
            reporter: 'spec',
            require: 'chai'
        },
        src: ['test/server/**/*.js']
    }
},

When I run the test, I get:

ReferenceError: chai is not defined

Here is my test:

'use strict';
/* global describe, it */
chai = require('chai');
expect = chai.expect;

describe('Persistence', function(){
    describe('#UserProvider', function(){
        it('should exist', function(){
            var UserProvider = require('../../server/providers/userProvider').UserProvider;
            expect(UserProvider).to.not.equal(undefined);
        });
    });
});

Thanks!

XUnit reporter captures all tests output

I'm using the following grunt task:

 mochaTest: {
              test: {
                options: {
                  reporter: 'Xunit',
                  captureFile: 'tmp/xunit-mochaTest.xml',
                },
                src: ['test/**/*.js'],

              }
         }

so I'm trying to get XUnit report. Unfortunately, in this case all the output from the running tests (so also console.log) is written to the file specified in the captureFile option.
I believe that there should be dist option added which would allow for capturing only the XUnit reporter output.

Log mocha errors to grunt console

When running mocha from command line, i see this error:

(function (exports, require, module, __filename, __dirname) { ui.view_rhmi.Wid
ReferenceError: ui is not defined

When running the same code via grunt-mocha-test, i see only that the task has failed.

Grunt exits early if test fails

If a test fails grunt exits. This quickly becomes a problem when chaining tasks. Is there anything I can do to prevent this from happening other than using --force?

Can't use mocha's ui option for third party ui extensions

It's currently not possible to load any Mocha UI other than the built-ins using grunt-mocha-test. This is the new Mocha instance is created before the require option is processed, which leaves you no hook to be able to alter the Mocha object before a new instance of it is created.

Given a folder with 3 files:
Gruntfile.js

module.exports = function(grunt) {
  grunt.loadNpmTasks('grunt-mocha-test');
  grunt.initConfig({
    mochaTest: {
      test:{
        options:{reporter:"spec", require:__dirname+"/example-ui.js", ui:"example-ui"},
        src:"test.js"
      }
    },
  });
  grunt.registerTask('default', ['mochaTest']);
};

test.js

test(function (done){
  check("a", "a");
  done();
});

example-ui.js

var Mocha = module.parent.require("mocha");
module.exports = function (suite){
  suite.on('pre-require', function(context){
    context.test = function (fn){
      suite.addTest(new Mocha.Test("stupid test", fn))
    }
    context.check = function (a, b){
      if(a != b)  throw ("Error "+ a + "!=" + b);
    }
  })
}
Mocha.interfaces["example-ui"] = module.exports;

The current code will throw an exception when you run grunt:
Warning: invalid interface "example-ui"

I'll be submitting a patch shortly that makes this scenario possible, by processing the require option before the new mocha instance is created.

Grunt 0.4 Release

I'm posting this issue to let you know that we will be publishing Grunt 0.4 on Monday, February 18th.

If your plugin is not already Grunt 0.4 compatible, would you please consider updating it? For an overview of what's changed, please see our migration guide.

If you'd like to develop against the final version of Grunt before Monday, please specify "grunt": "0.4.0rc8" as a devDependency in your project. After Monday's release, you'll be able to use "grunt": "~0.4.0" to actually publish your plugin. If you depend on any plugins from the grunt-contrib series, please see our list of release candidates for compatible versions. All of these will be updated to final status when Grunt 0.4 is published.

Also, in an effort to reduce duplication of effort and fragmentation in the developer community, could you review the grunt-contrib series of plugins to see if any of your functionality overlaps significantly with them? Grunt-contrib is community maintained with 40+ contributors—we'd love to discuss any additions you'd like to make.

Finally, we're working on a new task format that doesn't depend on Grunt: it's called node-task. Once this is complete, there will be one more conversion, and then we'll never ask you to upgrade your plugins to support our changes again. Until that happens, thanks for bearing with us!

If you have any questions about how to proceed, please respond here, or join us in #grunt on irc.freenode.net.

Thanks, we really appreciate your work!

Test suite failing on windows due to non blocking stdio flushing

I was debugging some issues I had trying to run some of my tests. To isolate the issues I decided to add a new test to grunt-mocha-test's suite.

I used npm install and then ran grunt

But I get many failing tests with "Uncaught AssertionError"'s, like these:

 9 failing

  1) grunt-mocha-test should run tests from the supplied files:
     Uncaught AssertionError: expected '\u001b[4mRunning "mochaTest:all" (mochaTest) task\u001b[24m\n\n\n  test1\n    ? should be ok: \u001b[2K\u001b[0G    V should
 be ok \n\n\n  1 passing (5 ms)\n\n\n\u001b[32mDone, without errors.\u001b[39m\n' to match /test2/


  2) grunt-mocha-test should report the number of test failures and exit grunt with an error on failed tests:
     Uncaught AssertionError: expected '\u001b[4mRunning "mochaTest:all" (mochaTest) task\u001b[24m\n\n\n  test\n    ? should fail: \u001b[2K\u001b[0G    1) should
fail\n\n\n  0 passing (5 ms)\n\n\u001b[33mWarning: Task "mochaTest:all" failed.\u0007 Use --force to continue.\u001b[39m\n' to match /Aborted due to warnings./

...

Which is odd since I see your travis-ci passing the build.

I'm running this on Windows Vista on node v0.10.10 and a fresh git checkout.

Error: 'suite not defined' even if the ui option is set to tdd.

Here is my Gruntfile:

'use strict';

module.exports = function (grunt) {
  // Show elapsed time at the end
  require('time-grunt')(grunt);
  // Load all grunt tasks
  require('load-grunt-tasks')(grunt);

  // Project configuration.
  grunt.initConfig({
    mochaTest: {
      test: {
        options: {
          ui: 'tdd'
        },
        src: ['test/**/*.js']
      }
    },
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      gruntfile: {
        src: 'Gruntfile.js'
      },
      lib: {
        src: ['lib/**/*.js']
      },
      test: {
        src: ['test/**/*.js']
      }
    },
    watch: {
      gruntfile: {
        files: '<%= jshint.gruntfile.src %>',
        tasks: ['jshint:gruntfile']
      },
      lib: {
        files: '<%= jshint.lib.src %>',
        tasks: ['jshint:lib', 'mochaTest']
      },
      test: {
        files: '<%= jshint.test.src %>',
        tasks: ['jshint:test', 'mochaTest']
      }
    }
  });

  // Default task.
  grunt.registerTask('default', ['jshint', 'mochaTest']);

};

I have defined ui as 'tdd' but I still get a "suite not defined" and "test not defined" error.

coverage threshold enforcement is not working

Hello,
I am trying to enforce a coverage threshold as demonstrated in the configuration examples but I get this result and grunt does not fail as expected.

Running "mochaTest:travis-cov" (mochaTest) task
Coverage: 0%
Code coverage below threshold: 0 < 50

Am I missing something ? I already move the threshold in a "config" block but the value is not taken into account (50 instead of 80).

package.json extract:

"config": {
    "travis-cov": {
        "threshold": 80
    }
}

Gruntfile.js extract:

mochaTest: {
    backend: {
        options: {
            reporter: 'spec',
            growl: true,
            require: 'coverage/blanket',
            clearRequireCache: true
        },
        src: ['server/tests/**/*.js']
    },
    'html-cov': {
        options: {
            reporter: 'html-cov',
            quiet: true,
            captureFile: 'coverage.html'
        },
        src: ['server/tests/**/*.js']
    },
    // The travis-cov reporter will fail the tests if the
    // coverage falls below the threshold configured in package.json
    'travis-cov': {
        options: {
            reporter: 'travis-cov'
        },
        src: ['server/tests/**/*.js']
    }
}

Prevent Mocha test failure from issuing grunt warning

When I'm running grunt-mocha-test in a watch, I want to be able to keep running it every time a file changes. If grunt-mocha-test calls grunt.fail.warn(), it'll kill the watch as well, unless I run the task with --force. Is there a way to prevent this from happening? If not, would you be amenable to a PR implementing that?

require option doesn't work

there is mocha.opts

--reporter dot
--require test/common
--timeout 5000

and grunt.js

/*global module:false*/
module.exports = function(grunt) {

  // Add our custom tasks.
  grunt.loadNpmTasks('grunt-mocha-test');

  // Project configuration.
  grunt.initConfig({
    mochaTest: {
      files: ['test/**/*.test.js']
    },
    mochaTestConfig: {
      options: {
        reporter: 'dot',
        require: 'test/common',
        timeout: 5000
      }
    },
    watch: {
      test: {
        files: ['test/**/*.test.js'],
        tasks: 'test'
      }
    }
  });

  grunt.registerTask('test', 'mochaTest');
  grunt.registerTask('default', 'test');
};

if I run mocha it works fine. But if i run grunt it gives me ReferenceError (because of variables defined in common.js)

0.8.1 fails to download via npm install (404 error)

Couldn't download 0.8.1--appears to be a packaging issue? 0.7.0 still works fine.

Close this if it's not useful.

D:\web\GitHub\FirebaseJoin [master +1 ~0 -2 | +14 ~16 -0 !]> npm install grunt-mocha-test --save-dev

npm http GET https://registry.npmjs.org/grunt-mocha-test
npm http 304 https://registry.npmjs.org/grunt-mocha-test
npm http GET https://registry.npmjs.org/grunt-mocha-test/-/grunt-mocha-test-0.8.1.tgz
npm http 404 https://registry.npmjs.org/grunt-mocha-test/-/grunt-mocha-test-0.8.1.tgz
npm ERR! fetch failed https://registry.npmjs.org/grunt-mocha-test/-/grunt-mocha-test-0.8.1.tgz
npm ERR! Error: 404 Not Found
npm ERR!     at WriteStream.<anonymous> (C:\Program Files\nodejs\node_modules\npm\lib\utils\fetch.js
:57:12)
npm ERR!     at WriteStream.EventEmitter.emit (events.js:117:20)
npm ERR!     at fs.js:1596:14
npm ERR!     at Object.oncomplete (fs.js:107:15)
npm ERR! If you need help, you may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <[email protected]>

npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\n
pm\\bin\\npm-cli.js" "install" "grunt-mocha-test" "--save-dev"
npm ERR! cwd D:\web\GitHub\FirebaseJoin
npm ERR! node -v v0.10.12
npm ERR! npm -v 1.2.32
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     D:\web\GitHub\FirebaseJoin\npm-debug.log
npm ERR! not ok code 0

NPM is bugging

I believe you should publish the 0.8.0 on NPM again because it seems replication failed on their cluster. I could update to 0.8.0 once yesterday after trying like 10 times but now even npmjs.org reports only 0.7.0 as the last version and don't seem to see the 0.8.0 at all.

Configuring blanket

My best efforts to configure blanket haven't yielded anything successful. I'm almost there, I think, but I'm unable to get blanket to load the correct files.

It looks as if I have everything set up correctly, but I can't seem to make any sense of the list of files returned from my pattern.

Some background: I'm looking into the generated coverage.html file to see what source code blanket is looking at. The project I'm working on is over here.

The issue is that I'm unable to determine where exactly blanket is basing its search from, as the list of files returned by blanket depend on the src of the mochaTest. If you change the src of mochaTest from test/*.js to lib/*.js, you'll get an entirely new list of files within coverage.html.

Further, the total list of files that blanket seems to be searching through seems to be missing out on the exact stuff I'm interested in. If you put . as the value of pattern, it only matches the test folder of the project, and everything in node_modules.

Am I missing something obvious here? How do I configure blanket to look into lib and tasks?

colors option not working

I tried for w hile to get this to work but couldn't. My workflow implied that grunt mocha test is run from a subprocess and color was disabled even with colors: true in the options.

I found out that setting

Mocha.reporters.Base.useColors = true;

does fix the color rendering.

Is it possible to patch in some way grunt-mocha-test so it sets this variable accordingly to options.colors?

Thanks a lot...

Mocha 1.18.0

It has landed with Promise support! ✨

We can now return Thenables instead of messing with done() .

Would be cool to have it in grunt-mocha-test too.

Running a test multiple times?

It seems I cannot run the same test (file) multiple times in the same grunt session.

The second time the same target is run it will complete with 0 tests executed.

Is this intended behaviour or a artefact of how the file input is normalised?

(use case: I have a integrity-check task that checks project health that I'd like to run at various stages of a complex build)

AMD Project Setup

Hello,

it may be bad style to start two threads about the same topic in two different "forums" but well...(other thread: mmoulton/grunt-mocha-cov#15) I am trying to achieve a HTML coverage report for my project but I am stuck.

I am using the grunt-mocha plugin to run the tests in a browser or via phantomsjs. So far so good. Sadly the plugin lacks support for coverage reports. Using grunt-mocha I can simply pass my test index.html as an option in my gruntfile. All dependencies defined via requirejs for the test are then fetched. This seems not possible using grunt-mocha-test as it is designed for server-tests.

I learned that I have to "wrap" require in order to be able to use it with nodejs like in this project: https://github.com/clubajax/mocha-bootstrap. Trying to run this example I get the message that no tests are found. My trials of applying the structure to my project ended with the same result. I am kind of clueless how exactly I am supposed to hand my requirejs-structured-tests to grunt-mocha-test in order to get a coverage report or what info about my project would be helpful here. Any help would be much appreciated.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.