Code Monkey home page Code Monkey logo

gulp-mocha's Introduction

gulp-mocha

Run Mocha tests

Keep in mind that this is just a thin wrapper around Mocha and your issue is most likely with Mocha.

Install

npm install --save-dev gulp-mocha

Usage

import gulp from 'gulp';
import mocha from 'gulp-mocha';

export default () => (
	gulp.src('test.js', {read: false})
		// `gulp-mocha` needs file paths so you cannot have any plugins before it.
		.pipe(mocha({reporter: 'nyan'}))
);

API

mocha(options?)

options

Type: object

Options are passed directly to the mocha binary, so you can use any its command-line options in a camelCased form. Arrays and key/value objects are correctly converted to the comma separated list format Mocha expects. Listed below are some of the more commonly used options:

ui

Type: string
Default: 'bdd'
Values: 'bdd' | 'tdd' | 'qunit' | 'exports'

The interface to use.

reporter

Type: string
Default: spec
Values: Reporters

The reporter that will be used.

This option can also be used to utilize third-party reporters. For example, if you npm install mocha-lcov-reporter you can then do use mocha-lcov-reporter as value.

reporterOptions

Type: object
Example: {reportFilename: 'index.html'}

Reporter specific options.

globals

Type: string[]

List of accepted global variable names, example ['YUI']. Accepts wildcards to match multiple global variables, e.g. ['gulp*'] or even ['*']. See Mocha globals option.

timeout

Type: number
Default: 2000

Test-case timeout in milliseconds.

bail

Type: boolean
Default: false

Bail on the first test failure.

checkLeaks

Type: boolean
Default: false

Check for global variable leaks.

grep

Type: string

Only run tests matching the given pattern which is internally compiled to a RegExp.

require

Type: string[]

Require custom modules before tests are run.

compilers

Type: string
Example: js:babel-core/register

Specify a compiler.

FAQ

Test suite not exiting

If your test suite is not exiting it might be because you still have a lingering callback, most often caused by an open database connection. You should close this connection or do the following:

export default () => (
	gulp.src('test.js')
		.pipe(mocha())
		.once('error', err => {
			console.error(err);
			process.exit(1);
		})
		.once('end', () => {
			process.exit();
		})
);

Or you might just need to pass the exit option:

export const test = () => (
	gulp.src(['test/**/*.js'], {read: false})
		.pipe(mocha({reporter: 'list', exit: true}))
		.on('error', console.error)
);

gulp-mocha's People

Contributors

abalmos avatar ai avatar alexgorbatchev avatar anru avatar davychiu avatar demisx avatar demurgos avatar dylanb avatar emohedano avatar floatdrop avatar gregberge avatar hooddanielc avatar jameskmonger avatar jlenoble avatar johanblumenberg avatar kahwee avatar kevva avatar kpdecker avatar marneborn avatar mathbruyen avatar mayeaux avatar mikelax avatar milang avatar miparnisari avatar morenoh149 avatar shellscape avatar sindresorhus avatar soboko avatar spiralx avatar stillesjo 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  avatar  avatar  avatar  avatar  avatar  avatar

gulp-mocha's Issues

Remove mocha dependency

Could we remove the mocha dependency and leave it up to the user to install it? there would need to be trust in the API to not change.

Mocha as peer dependency

I want to use peerigon/xunit-file plugin to generate xunit reports, but it depends on mocha. I have to install two versions of mocha.

node_modules
    ├── gulp-mocha
    │   └── node_modules
    │       └── [email protected]
    └── [email protected]

Why not to put mocha as peer dependency instead?

Exit code 1 not used on errors

I realize #45 has been closed and locked, but I do not believe this issue has been fixed. I am unable to get gulp-mocha to exit with anything other than exit code 0. I'd love to contribute a patch to fix this if anyone can point me in the right direction here.

Here's what I'm doing:

gulp.task('test', function (done) {
  gulp.src(testFiles)
  .pipe(require('gulp-mocha')({ reporter: 'spec' }))
  .on('error', console.log)
  .on('end', done);
});

Non 'AssertionError' with Async Mocha leads to timeout

I noticed a potential issue while using gulp-mocha with asynchronous mocha tests and an assertion library which did not throw an error with error.name equal to "AssertionError". Essentially, if an AssertionError is not thrown, then gulp-mocha will hang on that error until mocha's internal timeout is hit instead of continuing on to the next test.

I noticed that if I changed Line 34-39 of index.js to be this, the timeout problem was resolved:

if (runner && runner.uncaught) {
  runner.uncaught(err);
} else {
  clearCache();
  stream.emit('error', new gutil.PluginError('gulp-mocha', err));
}

I would worry that this might break some intended functionality, however, especially with users that would be expecting the error to be emitted by the stream.

Here is a link to a gist of the gulpfile and the test-simple file I was using to reproduce the issue. I also tinkered with catching the error from pipe.on('error', callback), but didn't come up with any results with that either.

Create clearer example on ignoring errors for watch mode

I was battling the fact that gulp crashes when gulp-mocha throws an error.

I have suffered quite a bit until stumbling upon this blessed SO question which guided me to emit "end" on the error handler in order to enable gulp to keep running.

I guess we could make it clearer that if you are running in some sort of watch mode you must "eat up" the error. My gulpfile ended up like this:

gulp = require 'gulp'
nodemon = require 'gulp-nodemon'
mocha = require 'gulp-mocha'
runningNodemon = false

gulp.task "test", ->
  gulp.src("test/**/*.coffee")
  .pipe(mocha(reporter: 'spec', compilers: "coffee:coffee-script/register"))
  .on('error', (e) -> console.log e.toString(); @emit 'end' if runningNodemon) # Eat up this error to continue running

gulp.task "nodemon", ->
  runningNodemon = true
  stream = nodemon script: "app.coffee", ext: "coffee", ignore: "gulpfile.coffee"
  stream.on("restart", ["test"])

gulp.task "default", ["test", "nodemon"]

I have created the boolean runningNodemon in order to emit the correct exit code in case of running a simple gulp test.

harmony flag

Is there a way to pass the harmony flag to mocha?

Get default options from `test/mocha.opts`

By default Mocha gets default options from test/mocha.opts. This plugin should did it too.

If I need to run only one test, I will execute mocha test/wrong.js. But in Travis CI gulp plugin is better. I want to combine this two runner methods, but I need common place to put options,

Run on a directory

Hi

Apologies if I'm missing something (because this is something that should be really simple) but I can't seem to be able to run gulp-mocha on a directory of files.

I have a directory structure like the following:

tests
  -- api
    -- controllers
      test1-spec.js
      test2-spec.js

and my gulp task is setup like the following:

gulp.task('api-tests', function () {
    gulp.src('tests/api/**')
    .pipe(mocha({
          reporter: 'spec'
    }));
});

When i run the task I get an error similar to cant find module tests/api/

What am i missing here? Or does this plugin not support this.

Consider integrating the problems gulp-spawn-mocha had tried to solve

The github project seems to have been removed, but from my email:

I was having problems with the cache, I don't have a link to anything it just seemed like a limitation of the way it was constructed. That try catch statement will get errors but you can still crash the process (e.g., and naively, process.exit(1). Furthermore, if any variables are set outside of modules (e.g., global scope) then those aren't cleared in the existing mocha plugin which I why I said that a new process will always start cleanly.

Support of mocha's `require` option

Cheers for this task. I am just trying to move things from grunt to gulp but am struggling with integrating the require-option from mocha which is also offered in the grunt-mocha-test-task.

Is there a way of using this option? Would it need some work on the task?

Gulp 4.0 mocha doesn't run tests

Mocha doesn't actually seem to run the tests when using the latest commit in the Gulp 4.0 branch. It just logs Starting 'mocha' and then exits.

Sample code:

function mochaTest() {
    gulp.src([
            'app/**/*.js',
            'config/**/*.js',
            'public/modules/**/*.js'
        ])
        .pipe(istanbul())
        .on('finish', function() {
            var server = require('./server');

            return gulp.src('./test/**/*.js')
                .pipe(mocha({
                    // reporter: 'mocha-lcov-reporter'
                }))
                .pipe(istanbul.writeReports())
                .once('end', function() {
                    server.kill();
                });
        });
}

require('./server') auto-starts the server and I just kill it at the end once mocha has run. This worked with 3.8.10, but with Gulp 4.0 no tests are actually run.

add option to run with node args

What do you all think about adding an option that would allow tasks to be run with args?

That way, we could do something like this to run tests with the debug argument

return gulp.src(paths.testFiles)
        .pipe(plugins.mocha({
             reporter: 'spec',
             timeout: 150000,
             grep: argv.grep
             nodeArgs: ['debug']

Support for --compilers option

On the command line I can run mocha --compilers coffee:coffee-script/register to run tests written in CoffeeScript. Alternately, I can put "--compilers coffee:coffee-script/register" in my test/mocha.opts file. It seems like neither of these approaches are supported in the current version of gulp-mocha.

How to output HTMLCov to a file?

gulp.task('test:android', function(){
  return gulp.src('android-*.js', {read: false})
    .pipe($.mocha({ui:'bdd',reporter: 'html-cov'}))
    .pipe(gulp.dest('./reports.html'));
});

In this case,I can only see the result in the console log,do I miss something?

Mocha output still async.

I suspected #47, but after update gulp-mocha output is still async. Any idea what should I investigate? My usage is pretty simple, it worked, but recent gulp-mocha or maybe mocha caused async gulp output.

Make gulp-mocha read options from mocha.opts

First of all, thank you for your work :)

By default, mocha will try to read options from a ./test/mocha.opts file, as described in their docs.

But gulp-mocha seem to ignore this file or override the configs from it.
I noticed while running the tests via mocha or make test in the command line: it would use the correct reporter I've set on the referred file; but while running it trough gulp test it would use the default "dot" reporter instead.

List mocha as a peerDependency

Today, mocha is listed as a dependency. I suggest moving it as a peerDependency for a few good reasons:

  • This allows for some plugins that extend mocha, such as mocha-clean, to work.
  • This allows the user to type mocha and have it run mocha tests in the same version of mocha.js as the one gulp-mocha would use.

When a test fails, the emitted error cannot be caught

The result is that the flush function for downstream plugins is not called.

Here is a test case that will fail

var through2 = require('through2');

it('should call the downstream flush function on test fail', function (done) {
    var reader = through2.obj(function (chunk, enc, cb) {
            cb();
        },
        function (cb) {
            cb();
            done();
        }),
        stream = mocha();

    stream.pipe(reader);
    stream.write(new gutil.File({path: 'fixture-fail.js'}));
    stream.end();
});

Option `streaming`

While we have streaming interface for most tasks, gulp-mocha is more like "batching" all incoming files inside and after end event runs them all in mocha. This is right thing to do, if you want to gather output from or emit error on end of all tests, that should be runned.

But this is not appropriate approach for stream, that comes from gulp.watch or gulp-watch plugin. When you decided to use watching - you got potentially endless stream of vinyl objects - and you got only one reasonable choice - restart all tests on every file that changed. That what this code does:

gulp.src(['./test/**/*','./lib/**/*'])
    .pipe(watch(function(events, cb) {
         gulp.src('./test/*').pipe(mocha()).on('end', cb);
    }))
    .on('error', console.log.bind(console));

As you can see, this example some how complicated and have duplicated gulp.src calls. In perfect world this can be written as:

gulp.src(['./test/**/*','./lib/**/*'])
    .pipe(watch({ emit: 'all' }))
    .pipe(grep('./test/*.js'))
    .pipe(mocha())
    .on('error', console.log.bind(console));

Which is little bit cleaner and easier to read (emit: 'all' means - generate all watched files when one file changes). But as was mentioned above, now mocha will not receive end event to stop gathering files and start running. Beside simplifying code there one interesting workflow, that developers should like:

gulp.src(['./test/**/*','./lib/**/*'])
    .pipe(watch())
    .pipe(grep('./test/*.js'))
    .pipe(mocha())
    .on('error', console.log.bind(console));

Without emit: all watch will be emit files down to stream as soon as it gets them. This code expample will work that way: on first run it will launch all tests squentally and when test file changes it will re-run only one bunch of tests (which is good on project with lots of tests, that are running some serious amount of time). Plus you can rerun file with tests just saving it in editor.

If last example is easy to implement - just run every file and don't overlap, emit: all is tough - mocha have no way to know when tests files is over and when to output final state (print that some of them are failing). Otherwise fail messages will sink in output:

[test 1]
ok
[test 2]
fail
[test 3]
ok
[test 4]
ok
...
[test 610]
ok
[test 611]
ok

The way around this emit: all problem is emit globend at the end of the current re-emitting batch, so mocha will now that is time to print out summary and reset runner.

Any suggestions on that are welcomed.

Gulp process does not end when testing an app

After a success or failure, if there's still part of the node process running, the gulp process never ends, and to return to the command line, you must CTRL+C out of Gulp.

Shouldn't gulp kill anything it requires, such as an app for testing?

Module did not self-register.

hi,

I'm not sure if it's a gulp-mocha problem per se, but it happens when I'm running test with gulp-mocha, so I'm posting it here.

gulpfile.js

var source_file_pattern = path.join(src_dir, '**/*.js');
var test_file_pattern = path.join(test_dir, '*.js');

gulp.task('mocha', function() {
    return gulp.src(test_file_pattern, { read: false })
        .pipe(mocha())
        .on('error', function(err) {
            notifier.notify({
                title: err.plugin,
                message: err.message
            });
        });
});

gulp.task('watch', function() {
    gulp.watch([source_file_pattern, test_file_pattern], ['mocha']);
});

gulp.task('default', ['watch']);

./test/test.js

var libxml = require('libxmljs');

describe('validation', function() {
    it('should be a valid document', function() {
        //
    });
});

so when I run gulp, it watches for file changes and runs the test once something changes. the first time the tests run fine, the second time this happens:

[12:35:03] Using gulpfile /Volumes/Macintosh HD 2/Projects/project/code/project.js/gulpfile.js
[12:35:03] Starting 'watch'...
[12:35:03] Finished 'watch' after 14 ms
[12:35:03] Starting 'default'...
[12:35:03] Finished 'default' after 13 μs
[12:35:22] Starting 'mocha'...


  validation
    ✓ should be a valid document


  1 passing (22ms)

[12:35:22] Finished 'mocha' after 129 ms
[12:35:24] Starting 'mocha'...
[12:35:24] 'mocha' errored after 35 ms
[12:35:24] Error in plugin 'gulp-mocha'
Message:
    Module did not self-register.
Stack:
Error: Module did not self-register.
    at Error (native)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at bindings (/Volumes/Macintosh HD 2/Projects/project/code/project.js/node_modules/libxmljs/node_modules/bindings/bindings.js:76:44)
    at Object.<anonymous> (/Volumes/Macintosh HD 2/Projects/project/code/project.js/node_modules/libxmljs/lib/bindings.js:1:99)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)

so this seems to have something to do with libxmljs (or its dependencies). however, when I do mocha --watch, I don't get the error.

versions:

% npm ls | ag '(gulp[^-]|mocha|libxmljs|bindings)'
├─┬ [email protected]
├─┬ [email protected]
├─┬ [email protected]
│ ├── [email protected]
├─┬ [email protected]

% node -v
v0.12.0

any ideas?

Output Redirection

I'm new to Node Streams and Gulp.js...

I can't figure out an elegant way to redirect mocha's output to a file (I want to use the tap format for Jenkins CI). I've resorted to using gulp-exec, but am sure I'm missing something simple.

Any help is greatly appreciated.

Difficulty handling test errors and watching?

For some reason I'm having difficulty hooking up watch and gulp-mocha... No matter what I do gulp always exits when error is emitted... I tried using plumber and on('error')

gulp.task 'dev:watch:server', ->
  mocha = require 'gulp-mocha'
  watch = require 'gulp-watch'
  plumber = require 'gulp-plumber'

  watch glob: 'build/server/**/test/**/*.js', emit: 'one', name: 'mocha', emitOnGlob: no, (stream) ->
    stream
      .pipe plumber()
      .pipe mocha reporter: 'spec'

plumber doesn't seem to be handling the error in this case...

Trying to use the same setup with other plugins works, for example compiling coffee files... if I have a syntax error, gulp reports it and continues watching

gulp.task 'dev:watch:coffee', ->
  coffee = require 'gulp-coffee'
  watch = require 'gulp-watch'
  plumber = require 'gulp-plumber'

  watch glob: SRC_FILES, emit: 'one', name: 'coffee', emitOnGlob: no, (stream) ->
    stream
      .pipe plumber()
      .pipe coffee bare: yes, sourceMap: yes
      .pipe gulp.dest BUILD

I even tried rewriting gulp-mocha using event-stream, the same plugin that gulp-coffee is using, same problem.

Mocha doesn't seem to be calling process.exit from anywhere other than the bin file.

What am I doing wrong? Any tips would be greatly appreciated!

Adding gulp-mocha to a task causes gulp to never exit (even though mocha's task was completed successfully)

I have the following in my gulp file:

gulp.task('lint', function() {
    // ...
});

gulp.task('test', function () {
    require('6to5/register');
    return gulp.src('test/**/*.js', {read: false})
        .pipe(mocha({reporter: 'spec'}));
});

gulp.task('default', ['lint', 'test'], function() {
    console.log('\n\n\nCompleted successfully!');
});

When running gulp, everything runs correctly, I get the "Completed succesfully" message, but the process doesn't exit. When I remove test from the list of dependencies for default, it exists as expected. (For comparison, removing lint had no effect).

I found gulpjs/gulp#416 but that was fixed several minor versions ago, and the last comment there indicates that the problem is likely to be with one of the plugins.

Callback for Mocha .run()

Mocha's programmatic .run() lets you pass a callback. For some things, it would be nice to be able to execute something after all the tests have ended, like killing a server or database connection or something like that. Can a callback key be added to the passed in options object that will be called before gulp-mocha emits all the stream messages to Gulp?

Nested orchestrations caused failing tests

When trying to use gulp-mocha to run the gulp tests, they would fail due to nested orchestrations (calling gulp.run inside a test).

This plugin should do something to avoid those scenarios. Unfortunately, the only way I can think of right now is to spawn a child process, but I am hoping you can think of a better way.

Issue with not ending stream correctly

I raised an issue with gulp (see here) about gulp failing to run a task after dependent task complete, we think it looks like it is an issue specifically with gulp-mocha not ending the stream after finishing.

gulp-mocha task doesn't exit after its completion when using with supertest

If I run my tests which use supertest, the process doesn't seem to exit. Had to use Ctrl+C to kill the process.

Not sure if this is an issue with supertest or gulp-mocha, but I think it could be an issue with gulp-mocha, because my tests run,and the process exits if I run directly with mocha

The gulp npm test task also doesn't exit, unless explicitly exited with process.exit(-1)

gulpfile.js

'use strict';
var gulp = require('gulp');


var mocha = require('gulp-mocha');
var testScriptPaths = ['tests/**/*.js'];

function handleError(err) {
  console.log(err.toString());
  this.emit('end');
}

gulp.task('test', function() {
    gulp.src(testScriptPaths)
        .pipe(mocha({ reporter: 'spec' }))
        .on('error', handleError);
});

gulp.task('npm', ['test'], function(done) {
    require('child_process').spawn('npm', ['test'], { stdio: 'inherit' })
    .on('close', function(e) {
        console.log(e);
        process.exit(-1);
        done();
    });
});


gulp.task('default', ['test'], function() {});

Test file

var should = require('chai').should(),
    express = require('express'),
    request = require('supertest');

describe('request.agent(app)', function(){
  var app = express();

  app.use(express.cookieParser());

  app.get('/', function(req, res){
    res.cookie('cookie', 'hey');
    res.send();
  });

  app.get('/return', function(req, res){
    if (req.cookies.cookie) res.send(req.cookies.cookie);
    else res.send(':(')
  });

  var agent = request.agent(app);

  it('should save cookies', function(done){
    agent
    .get('/')
    .expect('set-cookie', 'cookie=hey; Path=/', done);
  })

  it('should send cookies', function(done){
    agent
    .get('/return')
    .expect('hey', done);
  })
})

Cannot find module 'ms'

After the new update I'm getting this new error message:

Error in plugin 'gulp-mocha'
Message:
    Cannot find module 'ms'
Details:
    code: MODULE_NOT_FOUND

I'm not sure if the actual issue is with this plugin or a problem from gulp/mocha.

Running mocha is different from running gulp-mocha

My tests were failing with gulp-mocha and passing with mocha. The reason is that when using gulp-mocha, the global namespace does not seem to be cleared between test files. Eventually I resorted to using gulp-exec to call mocha per file, but am I doing something completely wrong or is this something fixable?

Cannot specify output file for coverage report

Forgive me if this functionality exists already, or if it's actually an issue with mocha, but I can't quite figure out how to make gulp-mocha output the report to an external file.

When running mocha on the command line you can specify an output file that the reporter will write to by ending your command with > file_name.ext like so:

mocha -R html-cov test/spec_init.coffee test/ > coverage/coverage.html

There doesn't seem to be any way to do this with gulp-mocha, but is that because it is a limitation of mocha? Or am I missing something super obvious?

Thanks very much.

Not exiting when tests that send HTTP requests are ran

This is one of my test files:

'use strict';

/* global before, after, describe, it */

var config = require('../server/config'),

    http = require('http'),
    should = require('should'),
    app = require('../server/app');

describe('API', function () {
    var server;

    before(function (done) {
        server = app.listen(config.port, function (err) {
            if (err) {
                done(err);
            } else {
                done();
            }
        });
    });

    after(function () {
        server.close();
    });

    it('should exist', function () {
        should.exist(app);
    });

    it('should be listening on port 8080', function (done) {
        http.get('http://localhost:8080/api', function (res) {
            res.statusCode.should.eql(200);

            done();
            console.log('DONE');
        });
    });
});

When I run it directly through Mocha, it works fine. When I run it using "gulp test", it doesn't exit—although "DONE" is logged to the console.

Here is my Gulp task:

gulp.task('test', function() {
    return gulp.src(['tests/**/*.spec.js'], { read: false })
        .pipe(plugins.mocha({
            reporter: 'spec'
        }))
        .on('error', gutil.log);
});

It works fine when I use setTimeout() instead of making an HTTP request.

Add option for compilers flag or explicitly state how to specify this in the docs

Sorry if this is the wrong place to ask this, but can we add something for the mocha --compiler flag? I tried looking through the source and couldn't easily figure out how to explicitly set this option. However, when I just do add a require('mycompiler') at the top of my gulpfile, it somehow magically runs during the mocha task. I see the readme explains how to do this for coffeescript, but I have my own compiler which I use for jsx to js transormations (reactjs).

For example, running from the command line mocha --compilers .:my_compiler.js test/**/*.js

Globals & Require not working?

I have a feeling it's a simple solution but I have tried it all.

gulp.task('test:server', function() {
  return gulp.src('test/server/**/*.spec.js', {read: false})
          .pipe(mocha({
            reporter: 'list',
            require: {
              chai: require('chai'),
              expect: require('chai').expect,
              chaiAsPromised: require('chai').use(require('chai-as-promised')),
              sinon: require('sinon')
            },
            globals: {
              chai: require('chai'),
              expect: require('chai').expect,
              chaiAsPromised: require('chai').use(require('chai-as-promised')),
              sinon: require('sinon')
            }
          }));
});

Gets error:

18:17:46] Starting 'test:server'...

  1) Trial should output nothing

  0 passing (4ms)
  1 failing

  1) Trial should output nothing:
     ReferenceError: expect is not defined
      at Context.<anonymous> (test/server/cart/cart.spec.js:6:5)



[18:17:46] 'test:server' errored after 103 ms
[18:17:46] Error in plugin 'gulp-mocha'
Message:
    1 test failed.

Failing tests causes gulp watch process to terminate

Example:

[gulp] Running 'watch'...
[gulp] Finished 'watch' in 12 ms
[gulp] Running 'test'...
[gulp] Finished 'test' in 219 ms


  Square
    ✓ should return the square of the input
    1) should fail
    ✓ should return -1 on input 1 for some reason


  2 passing (5ms)
  1 failing

  1) Square should fail:
     AssertionError: true == false
      at Context.<anonymous> (/Users/nissen/code/gulp-test/test/utilsTests.js:11:12)
      at Test.Runnable.run (/Users/nissen/code/gulp-test/node_modules/gulp-mocha/node_modules/mocha/lib/runnable.js:221:32)
      at Runner.runTest (/Users/nissen/code/gulp-test/node_modules/gulp-mocha/node_modules/mocha/lib/runner.js:378:10)
      at /Users/nissen/code/gulp-test/node_modules/gulp-mocha/node_modules/mocha/lib/runner.js:456:12
      at next (/Users/nissen/code/gulp-test/node_modules/gulp-mocha/node_modules/mocha/lib/runner.js:303:14)
      at /Users/nissen/code/gulp-test/node_modules/gulp-mocha/node_modules/mocha/lib/runner.js:313:7
      at next (/Users/nissen/code/gulp-test/node_modules/gulp-mocha/node_modules/mocha/lib/runner.js:251:23)
      at Object._onImmediate (/Users/nissen/code/gulp-test/node_modules/gulp-mocha/node_modules/mocha/lib/runner.js:280:5)
      at processImmediate [as _immediateCallback] (timers.js:330:15)




events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: gulp-mocha: 1 test failed.
    at Stream.<anonymous> (/Users/nissen/code/gulp-test/node_modules/gulp-mocha/index.js:18:32)
    at Runner.<anonymous> (/Users/nissen/code/gulp-test/node_modules/gulp-mocha/node_modules/mocha/lib/runner.js:581:5)
    at Runner.EventEmitter.emit (events.js:117:20)
    at /Users/nissen/code/gulp-test/node_modules/gulp-mocha/node_modules/mocha/lib/runner.js:588:10
    at /Users/nissen/code/gulp-test/node_modules/gulp-mocha/node_modules/mocha/lib/runner.js:522:7
    at next (/Users/nissen/code/gulp-test/node_modules/gulp-mocha/node_modules/mocha/lib/runner.js:251:23)
    at Object._onImmediate (/Users/nissen/code/gulp-test/node_modules/gulp-mocha/node_modules/mocha/lib/runner.js:280:5)
    at processImmediate [as _immediateCallback] (timers.js:330:15)

The watch process is terminated due to an Error being thrown in index.js:

if (errCount > 0) {
                    return this.emit('error', new Error('gulp-mocha: ' + errCount + ' ' + (errCount === 1 ? 'test' : 'tests') + ' failed.'));
                }

Without that statement, the watch process continues as expected when tests fail.

Gulp-Mocha fails to exit, but Mocha does

Hi,

I am running a simple test (its failing, but that a separate issue).

Using:

"gulp-mocha": "^1.0.0",

When I run this using Gulp-Mocha (it happens on Travis as well), it does not exit the testing execution, but when I run this using Mocha, it fails, and exits back to the command prompt.

var assert = require("assert"),
    elasticsearch = require('elasticsearch'),
    client;

    client = new elasticsearch.Client();

    describe(' people', function(){

    beforeEach(function(done){

        //in Gulp Mocha this stops the test runner exiting
        //that this does not work is not this issue.
        client.deleteByQuery({
            index: 'people',
            q: '*'
        }, function (error, response) {
            done();
        });


       //If i just do done(), it will exit. in both.
       //done();

    });

    describe('add a entry into the index', function(){
        it('should add Dave as a person to the database', function(done){
            assert.equal(1,1);
        });
    });
});

gulp-mocha dies silently when running too many test files

gulp-mocha uses through2 package internally which has highWaterMark option set by default to 16:
https://github.com/rvagg/through2/blob/ee2720526f58d5f58e0af5179ca170dbfdf34fbf/through2.js#L88

I have 36 test files in my project and due to this option tests just do not run and gulp dies without any error message (it allows me to pass only 16 test files to gulp-mocha; when I try to pass more via gulp pipe it just exits with exit code 0).

Can you please expose through2 options so I can increase its highWaterMark limit manually in my project's gulpfile or can you fix this issue in any other way so running multiple test files is possible?

gulp-mocha break the pipe spirit

For minimalist test file, my gulpfile insert on the flow the production code at the beginning of the corresponding test file.

dummy.coffee will be concatenated before dummy_test.coffee
any.coffee will be concatenated before any_test.coffee
but gulp-mocha open file by name and don't use the pipe modified content...
That's why i need to break the pipe with temp files as extra step.

gulp-mocha could use file.content if present and only load it from filesystem file if read:false have been used. I think this behavior more intuitive.

As example, my actual gulpfile.

gulp = require 'gulp'
$ = require('gulp-load-plugins')()
del = require 'del'

chemins =
  tests: 'src/**/*_test.coffee'
  tmp: 'tmp/'

gulp.task 'test', ->
  gulp.src(chemins.tests,
#    read: false
  )
  .pipe($.wrapper(
      header: (file)->
        filename = file.path.split('/').pop().split('\\').pop()
        "@@include('"+filename.replace(/_test/, '')+"')\n"
  ))
  .pipe($['fileInclude']())
  .pipe(gulp.dest(chemins.tmp+'test/'))
  gulp.src(chemins.tmp+'test/**/*.coffee',
    read: false
  )
  .pipe($.mocha(
      reporter: 'spec'
      globals:
        should: require('should')
    ))

Requiring any non-server file causes tests to fail

I have a very basic test set running, and if I require any file other than my test_server.coffee file in my gulpfile, the test suite fails. This works just fine:

gulp     = require 'gulp'
mocha    = require 'gulp-mocha'

gulp.task 'mocha', () ->
  gulp.src './test/*.coffee', { read: false }
    .pipe mocha
      reporter: 'nyan'
      globals: should: require 'should'

But this will break all the tests:

gulp     = require 'gulp'
mocha    = require 'gulp-mocha'
foobar   = require './path-to-file-that-exists'

gulp.task 'mocha', () ->
  gulp.src './test/*.coffee', { read: false }
    .pipe mocha
      reporter: 'nyan'
      globals: should: require 'should'

This causes require statements in my test suite to return undefined, and that subsequently causes tests to fail, e.g.: TypeError: Cannot call method 'setup_test_db' of undefined.

The mocha command will run the test suite just fine either way; it is only the gulp mocha command that causes the error.

Any ideas on if this is a bug and how to fix?

Explain `globals`

The globals option is not explained but it would be great to give at least pointer. Being new to Gulp and nodejs and I've no idea what it is.

PS: I'm trying to pass arguments from Gulp to Mocha and I'm guessing this might be a way.

Gulp goesn’t use exit code 1 on Mocha errors

I use gulp-mocha 0.5.0 have task:

gulp.task('test', function () {
    require('./');
    var mocha = require('gulp-mocha');

    return gulp.src('test/*.js', { read: false })
        .pipe(mocha());
});

When I start task, I have mocha failed tests, but exit code is 0:

postcss → n gulp test
[01:26:51] Using gulpfile ~/Dev/postcss/gulpfile.js
[01:26:51] Starting 'test'...

  [01:26:52] Finished 'test' after 671 ms
․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․
  ․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․
  ․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․․
  ․․․․․․․․․․․․․․

  189 passing (198ms)
  4 failing

  1) source maps changes previous source map:

      AssertionError: expected { source: '/a.css', line: 1, column: 4, name: null } to equal { source: 'a.css', line: 1, column: 4, name: null }
      + expected - actual

       {
         "column": 4,
         "line": 1,
         "name": null,
      +  "source": "a.css"
      -  "source": "/a.css"
       }

      at Assertion.prop.(anonymous function) [as eql] (/home/ai/Dev/postcss/node_modules/should/lib/should.js:61:14)
      at Context.css (/home/ai/Dev/postcss/test/map.js:95:17)
      at callFn (/home/ai/Dev/postcss/node_modules/mocha/lib/runnable.js:223:21)
      at Test.Runnable.run (/home/ai/Dev/postcss/node_modules/mocha/lib/runnable.js:216:7)
      at Runner.runTest (/home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:373:10)
      at /home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:451:12
      at next (/home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:298:14)
      at /home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:308:7
      at next (/home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:246:23)
      at Object._onImmediate (/home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:275:5)

  2) source maps uses map from subdir:

      AssertionError: expected '/a.css' to equal '../../a.css'
      + expected - actual

      +"../../a.css"
      -"/a.css"

      at Assertion.prop.(anonymous function) [as eql] (/home/ai/Dev/postcss/node_modules/should/lib/should.js:61:14)
      at Context.$__0.doubler.process.from (/home/ai/Dev/postcss/test/map.js:260:24)
      at callFn (/home/ai/Dev/postcss/node_modules/mocha/lib/runnable.js:223:21)
      at Test.Runnable.run (/home/ai/Dev/postcss/node_modules/mocha/lib/runnable.js:216:7)
      at Runner.runTest (/home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:373:10)
      at /home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:451:12
      at next (/home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:298:14)
      at /home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:308:7
      at next (/home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:246:23)
      at Object._onImmediate (/home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:275:5)

  3) source maps works with different types of maps:

      AssertionError: expected '/a.css' to equal 'a.css'
      + expected - actual

      +"a.css"
      -"/a.css"

      at Assertion.prop.(anonymous function) [as eql] (/home/ai/Dev/postcss/node_modules/should/lib/should.js:61:14)
      at Context.$__0.doubler.process.from (/home/ai/Dev/postcss/test/map.js:319:28)
      at callFn (/home/ai/Dev/postcss/node_modules/mocha/lib/runnable.js:223:21)
      at Test.Runnable.run (/home/ai/Dev/postcss/node_modules/mocha/lib/runnable.js:216:7)
      at Runner.runTest (/home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:373:10)
      at /home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:451:12
      at next (/home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:298:14)
      at /home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:308:7
      at next (/home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:246:23)
      at Object._onImmediate (/home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:275:5)

  4) source maps miss source content on request:
     Error: "../a.css" is not in the SourceMap.
      at SourceMapConsumer_sourceContentFor [as sourceContentFor] (/home/ai/Dev/postcss/node_modules/source-map/lib/source-map/source-map-consumer.js:375:13)
      at Context.<anonymous> (/home/ai/Dev/postcss/test/map.js:364:29)
      at callFn (/home/ai/Dev/postcss/node_modules/mocha/lib/runnable.js:223:21)
      at Test.Runnable.run (/home/ai/Dev/postcss/node_modules/mocha/lib/runnable.js:216:7)
      at Runner.runTest (/home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:373:10)
      at /home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:451:12
      at next (/home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:298:14)
      at /home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:308:7
      at next (/home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:246:23)
      at Object._onImmediate (/home/ai/Dev/postcss/node_modules/mocha/lib/runner.js:275:5)

postcss →

Travis CI also get exit code 0: https://travis-ci.org/ai/postcss/builds/29471330

Add support to run Mocha specs with PhantomJS

First of all: Thank you for your time and efforts on making this plugin 👍

And now the question:

Are you planning on adding the option to run the specs through PhantomJS? It would be nice to have the chance to run the Mocha tests of our web apps using Gulp.

Thanks a lot!

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.