EzDevInfo.com

mocha

mocha - simple, flexible, fun javascript test framework for node.js & the browser. (BDD, TDD, QUnit styles via interfaces) Mocha - the fun, simple, flexible JavaScript test framework

How to run a single test with Mocha?

I use Mocha to test my JavaScript stuff. My test file contains 5 tests. Is that possible to run a specific test (or set of tests) rather than all the tests in the file?


Source: (StackOverflow)

What are the differences between mocha, chai, karma, jasmine, should.js, etc. testing frameworks?

I'm new to testing, and I see that there are many options to work with and I'm confused.

I would like to know the differences between the following frameworks, especially what service each framework provides, and why we need so many frameworks to have one flow of testing?

  1. mocha

  2. chai

  3. karma

  4. jasmine

  5. should.js

If anyone has more options to recommend, I would be happy to hear it.

Thanks!


Source: (StackOverflow)

Advertisements

How to test nodejs backend code with Karma (testacular)

How do I setup Karma to run my backend unit tests (written with Mocha)? If I add my backend test script to the files = [], it fails stating that require is undefined.


Source: (StackOverflow)

Jasmine vs. Mocha Javascript testing for Rails 3.1+ [closed]

I have experience with Jasmine and do like it quite a bit. Does anyone have experience with both Jasmine and Mocha, specifically for Rails? I am wondering if it's worth switching to.

Many thanks in advance,

Chris


Source: (StackOverflow)

What is the difference between assert, expect and should in Chai?

What is the difference between assert, expect and should, and when to use what?

assert.equal(3, '3', '== coerces values to strings');

var foo = 'bar';

expect(foo).to.equal('bar');

foo.should.equal('bar');

Source: (StackOverflow)

How to specify test directory for mocha?

Mocha tries to find test files under test by default, how to specify another dir, e.g. server-test?


Source: (StackOverflow)

Code coverage with mocha

I am using mocha for testing my nodejs application. I am not able to figure out how to use its code coverage feature. I tried googling it but din't find any proper tutorial. Please help.


Source: (StackOverflow)

When using mocha for testing how do i increase timeout for a particular test case

I am using mocha for testing my app, in the before condition I have called an API which does a network request for data and then on the response I am calling the done method. The network API takes longer than usual and the before block for the test case fails due to timeout, since the default timeout for mocha is 2sec's. How do I increase the timeout for my particular test case?


Source: (StackOverflow)

Mocha / Chai expect.to.throw not catching thrown errors

I'm having issues getting Chai's expect.to.throw to work in a test for my node.js app. The test keeps failing on the thrown error, but If I wrap the test case in try and catch and assert on the caught error, it works.

Does expect.to.throw not work like I think it should or something?

it('should throw an error if you try to get an undefined property', function (done) {
  var params = { a: 'test', b: 'test', c: 'test' };
  var model = new TestModel(MOCK_REQUEST, params);

  // neither of these work
  expect(model.get('z')).to.throw('Property does not exist in model schema.');
  expect(model.get('z')).to.throw(new Error('Property does not exist in model schema.'));

  // this works
  try { 
    model.get('z'); 
  }
  catch(err) {
    expect(err).to.eql(new Error('Property does not exist in model schema.'));
  }

  done();
});

The failure:

19 passing (25ms)
  1 failing

  1) Model Base should throw an error if you try to get an undefined property:
     Error: Property does not exist in model schema.

Source: (StackOverflow)

Mock/Test Mongodb Database Node.js

I am learning nodejs and I have a mongodb database with which i have to interact with. I am currently thinking of using mocha for a unit test framework and zombie.js for a acceptance test framework. I was wondering how could I do full scale acceptance tests which hit the mongodb database. Is there a framework/module that helps with replacing the database with a test database or does either mocha or zombie.js have functionality that can easily be used to replace the database.

Also is there a framework that is similar to the idea of factories (instead of fixtures) in creating database objects.

A similar concept that I have encountered in the rails world is in rspec, there is a spec_helper.rb file which runs before the tests are run which set the projects configuration to decide which database to hit when running tests. And it uses database_cleaner to clean out the test database before tests are run. For factories, i have used Factory girl to create factory objects from database schema again in the rails world.

Thanks


Source: (StackOverflow)

How do I test AngularJS code using Mocha?

Basically, I'm quite experienced with Mocha (written thousands of unit tests), and I'm quite new to AngularJS (written just my first project).

Now I am wondering how I might unit test all the AngularJS stuff using Mocha.

I know that Mocha runs in the browser, and I have already done this. But how do I structure and setup things?

I guess I need to:

  • Load AngularJS
  • Load Mocha
  • Load my tests

Within each of the tests, I need to load a controller, a service, ... to test. How do I do that? I am not using require.js or something like that, the files are just script files with basically the following content:

angular.controller('fooController', [ '$scope', function ($scope) {
  // ...
}]);

How do I reference and instantiate that controller within a test? The same holds true for services, directives, ...

Do I need to create mocks for $scope, $http & co. for myself, or is there some help?

Please note that I am aware that there is the Karma test runner (formerly known as Testacular), but I do not want to switch my test runner completely.


Source: (StackOverflow)

Testing javascript with Mocha - how can I use console.log to debug a test?

I am using the javascript test-runner "Mocha".

I have a test that is failing, so I would to debug it using console.log.

But when the tests are run, there is no output (only the test results from Mocha). It seems like Mocha has captured and suppressed my console.log output!

How can I get Mocha to show my output? (at for tests that fail)?

EDIT:

Huge apologies! — console.log does work during tests! I must have been expecting it to suppress the output, and I didn't properly check my own code. Thanks for responding. So... that being said... maybe it actually would be nice to suppress the output for tests that pass? hmm...

On a related note: I want to use console.log because I am having a lot of trouble trying to get the Eclipse debugger to connect to node.js.

Am I the only one who finds this tricky? How do you guys debug node.js? With a debugger, or with console.log statements?


Source: (StackOverflow)

Why do I see "define not defined" when running a Mocha test with RequireJS?

I am trying to understand how to develop stand-alone Javascript code. I want to write Javscript code with tests and modules, running from the command line. So I have installed node.js and npm along with the libraries requirejs, underscore, and mocha.

My directory structure looks like this:

> tree .
.
├── node_modules
├── src
│   └── utils.js
└── test
    └── utils.js

where src/utils.js is a little module that I am writing, with the following code:

> cat src/utils.js 
define(['underscore'], function () {

    "use strict";

    if ('function' !== typeof Object.beget) {
        Object.beget = function (o) {
            var f = function () {
            };
            f.prototype = o;
            return new f();
        };
    }

});

and test/utils.js is the test:

> cat test/utils.js 
var requirejs = require('requirejs');
requirejs.config({nodeRequire: require});

requirejs(['../src/utils'], function(utils) {

    suite('utils', function() {
        test('should always work', function() {
            assert.equal(1, 1);
        })
    })

});

which I then try to run from the top level directory (so mocha sees the test directory):

> mocha

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: Calling node's require("../src/utils") failed with error: ReferenceError: define is not defined
    at /.../node_modules/requirejs/bin/r.js:2276:27
    at Function.execCb (/.../node_modules/requirejs/bin/r.js:1872:25)
    at execManager (/.../node_modules/requirejs/bin/r.js:541:31)
    ...

So my questions are:

  • Is this the correct way to structure code?
  • Why is my test not running?
  • What is the best way to learn this kind of thing? I am having a hard time finding good examples with Google.

Thanks...

[sorry - momentarily posted results from wrong code; fixed now]

PS I am using requirejs because I also want to run this code (or some of it) from a browser, later.

Update / Solution

Something that is not in the answers below is that I needed to use mocha -u tdd for the test style above. Here is the final test (which also requires assert) and its use:

> cat test/utils.js 

var requirejs = require('requirejs');
requirejs.config({nodeRequire: require});

requirejs(['../src/utils', 'assert'], function(utils, assert) {

    suite('utils', function() {
        test('should always work', function() {
            assert.equal(1, 1);
        })
    })

});
> mocha -u tdd

  .

  ✔ 1 tests complete (1ms)

Source: (StackOverflow)

Supertest custom express server in node

Please be gentle with me. I'm new to async coding and have been thrown headfirst into an intensive project using node to develop and API server. I'm loving it but some things aren't coming naturally.

Our project is built using express js. We have a file, server.js where we instantiate an express server which in turn instantiates our router and so on. I need to integration test this now (partially) complete server. Normally what I do is from the command line run '%node server.js' and then using either python requests or curl make requests and check the responses.

Now I've been tasked with writing a unit and integration test suite so that we can automate our testing going forward. I've been using mocha and now am trying to use supertest for the integration testing. The problem is that supertest expects a server object which it then applies tests to however our file that builds our server object doesn't return anything. I don't want to modify that file so I am stumped as to how to access the server object to use for testing.

My server file looks (in part) like this:

var express = require('express')

var app = express();

// Express Configuration
app.use(express.favicon()); //handles favicon request, which keeps it out of the log when using a browser :)
app.use(express.bodyParser()); //slurps up the body in chunks the node.js way :)
// ...and so on

and my mocha test file looks like this

var request = require('supertest')
  , app     = require('../server.js')
  , assert  = require("assert");

describe('POST /', function(){
  it('should fail bad img_uri', function(done){
    request(app)
        .post('/')
        .send({
            'img_uri' : 'foobar'
        })  
        .expect(500)
        .end(function(err, res){
        console.dir(err)
        console.dir(res)
            done();
        })  
  })    
})

when I run this test I get a complaint about the app object not having a method named address. My question is, is there a way I can require/call the server.js file so that the app object will be in scope? Or am I going about this wrong. I also played around a little bit with using http.js to make calls directly to the server but didn't have luck that way either. Thanks!


Source: (StackOverflow)

How do I test 'normal' (non-Node specific) JavaScript functions with Mocha?

This seems like it should be extremely simple; however, after two hours of reading and trial-and-error without success, I'm admitting defeat and asking you guys!

I'm trying to use Mocha with Should.js to test some JavaScript functions, but I'm running into scoping issues. I've simplified it down to the most basic of test cases, but I cannot get it working.

I have a file named functions.js, which just contains the following:

function testFunction() {
    return 1;
}

And my tests.js (located in the same folder) contents:

require('./functions.js')

describe('tests', function(){
    describe('testFunction', function(){
        it('should return 1', function(){
            testFunction().should.equal(1);
        })
    })
})

This test fails with a ReferenceError: testFunction is not defined.

I can see why, because most of the examples I've found either attach objects and functions to the Node global object or export them using module.exports—but using either of these approaches means my function code would throw errors in a standard browser situation, where those objects don't exist.

So how can I access standalone functions which are declared in an separate script file from my tests, without using Node-specific syntax?


Source: (StackOverflow)