EzDevInfo.com

chai

BDD / TDD assertion framework for node.js and the browser that can be paired with any testing framework. Home - Chai

Setting up karma, chai, requirejs, chai-jquery

I'm close to getting our tests to run with Karma but I'm missing the last step (I think), getting chai-jquery to behave, I've tried two different plugins https://www.npmjs.com/package/karma-chai-jquery and https://www.npmjs.com/package/karma-jquery-chai with no success, even after following the specified order set in their various github issues or readme files.

This is my tests-main.js file

var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;

Object.keys(window.__karma__.files).forEach(function(file) {
    if (TEST_REGEXP.test(file)) {
        // Normalize paths to RequireJS module names.
        allTestFiles.push(file);
    }
});

require.config({

    baseUrl: '/base',

    paths: {
        'chai':             'node_modules/chai/chai',
        'chai-jquery':      'node_modules/chai-jquery/chai-jquery',
        'jquery':           '//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery',
        'underscore':       '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min',
        'sn/sn-underscore': 'static/scripts/sn/sn-underscore',
        'vendor/jquery-ui': '//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min'
    },

    deps: allTestFiles,

    callback: window.__karma__.start
});

This is my karma.conf.js (removed all non-crucial or default options)

// Karma configuration
module.exports = function(config) {
    config.set({
        basePath: '',
        // Can't use chai in here for whatever reason
        frameworks: ['mocha', 'requirejs'],
        files: [
            'static/scripts-test/test-main.js',
            {pattern: 'node_modules/chai/chai.js', included: true},
            {pattern: 'static/scripts-test/**/*.js', included: false},
            {pattern: 'static/scripts/sn/**/*.js', included: false}
        ],
        exclude: [
            'static/scripts/global.js'
        ],
        browsers: ['PhantomJS']
    });
};

This is a "working" spec file, it correctly uses gets the references to chai and jquery, but loading chai-jquery fails every time.

define([
    'chai',
    'jquery',
    'static/scripts/sn/widgets/dismissable'
], function(chai, $) {
    chai.should();
    chai.expect();

    describe('Dismissable', function() {
        var $el = $('</p>'),
            closeBtnSel = '.js-dismissable-close-btn';

        beforeEach(function() {
            $('body').append('<div id="fixtures"></div>');
            $el.appendTo('#fixtures').dismissable({closeFn: 'hide'});
        });

        afterEach(function() {
            $el.remove();
        });

        it('should correctly create the HTML', function() {
            $(closeBtnSel).should.exist;
            $el.should.have.class('dismissable');
        });
    });
});

The error that I get is:

TypeError: 'undefined' is not an object (evaluating '$(closeBtnSel).should.exist')

This is my directory structure:

- static/
  - scripts/
  - scripts-test/
    - test-main.js
- node_modules/
- karma.conf.js

And finally, my package.json

{
  "devDependencies": {
    "chai": "^2.3.0",
    "chai-jquery": "^2.0.0",
    "jquery": "^2.1.4",
    "karma-chai": "^0.1.0",
    "karma-mocha": "^0.1.10",
    "karma-requirejs": "*",
    "mocha": "^2.2.5",
    "requirejs": "^2.1.18",
    "should": "^6.0.1"
  }
}

Some of the errors I usually get:

When changing the order of the frameworks in the karma.conf

    throw error('No provider for "' + name + '"!');
                ^
    Error: No provider for "framework:chai"! (Resolving: framework:chai)

even after installing the plugin

Sometimes I'll get something like this:

Error: Mismatched anonymous define() module: function ($) {
        return function (chai, utils) {
          return chaiJquery(chai, utils, $);
        };
      }

Any help would be greatly appreciated here, I can't wrap my head around this.

EDIT: Small change based on recommendation from Louis


Source: (StackOverflow)

How does the chai expect function work?

From chai's api you've got code like this:

.exist

Asserts that the target is neither null nor undefined.

var foo = 'hi'
  , bar = null
  , baz;

expect(foo).to.exist;
expect(bar).to.not.exist;
expect(baz).to.not.exist;

How does that exist part work? The expect function returns an object, then there's simply a property lookup on the "to" object. That's simply a property evaluation though isn't it? The only thing that would make sense to me is if the exist property is a getter method.

What's the go?


Source: (StackOverflow)

Advertisements

How to write a test that checks for multiple types in chai

I'm trying to write a test that would pass if the input is either a string or a null value

in chai is there something similar to

expect(foo).to.be.a('string').or.a('null')

If not what would be best practice when writing a test that needs to check for multiple types?


Source: (StackOverflow)

Chai: how to test for undefined with 'should' syntax

Building on this tutorial testing an angularjs app with chai, I want to add a test for an undefined value using the "should" style. This fails:

it ('cannot play outside the board', function() {
  scope.play(10).should.be.undefined;
});

with error "TypeError: Cannot read property 'should' of undefined", but the test passes with the "expect" style:

it ('cannot play outside the board', function() {
  chai.expect(scope.play(10)).to.be.undefined;
});

How can I get it working with "should"?


Source: (StackOverflow)

How to get mocha with chai assert to report file/line number?

I'm using mocha with chai.assert for my tests. Errors are caught and reported, but they don't show a file/line number where they happen. I'm used to having location information with tests in other languages, it's otherwise hard to figure out which assert failed.

Is there some way to get location information with mocha/chai/assert?


Source: (StackOverflow)

How to I properly test promises with mocha and chai?

The following test is behaving oddly:

it('Should return the exchange rates for btc_ltc', function(done) {
    var pair = 'btc_ltc';

    shapeshift.getRate(pair)
        .then(function(data){
            expect(data.pair).to.equal(pair);
            expect(data.rate).to.have.length(400);
            done();
        })
        .catch(function(err){
            //this should really be `.catch` for a failed request, but
            //instead it looks like chai is picking this up when a test fails
            done(err);
        })
});

How should I properly handle a rejected promise (and test it)?

How should I properly handle a failed test (ie: expect(data.rate).to.have.length(400);?

Here is the implementation I'm testing:

var requestp = require('request-promise');
var shapeshift = module.exports = {};
var url = 'http://shapeshift.io';

shapeshift.getRate = function(pair){
    return requestp({
        url: url + '/rate/' + pair,
        json: true
    });
};

Source: (StackOverflow)

Testing for errors thrown in Mocha

I'm hoping to find some help with this problem. I'm trying to write tests for an application I am writing. I have distilled the problem in to the following sample code. I want to test that an error was thrown. I'm using Testacular as a test runner with mocha as the framework and chai as the assertion library. The tests run, but the test fails because an error was thrown! Any help is greatly appreciated!

function iThrowError() {
    throw new Error("Error thrown");
}

var assert = chai.assert,
    expect = chai.expect;
describe('The app', function() {
    describe('this feature', function() {
        it("is a function", function(){
            assert.throw(iThrowError(), Error, "Error thrown");
        });
    });
});

Source: (StackOverflow)

Testing JS exceptions with Mocha/Chai

Trying to test some code that throws an exception with Mocha/Chai, but having no luck, here's the simple code I'm trying to test:

class window.VisualizationsManager

  test: ->
    throw(new Error 'Oh no')

Here is my test:

describe 'VisualizationsManager', ->

  it 'does not permit the construction of new instances', ->

    manager = new window.VisualizationsManager

    chai.expect(manager.test()).to.throw('Oh no')

However, when I run the spec, the test fails and throws the exception.

Failure/Error: Oh no

what am I doing wrong here?


Source: (StackOverflow)

Chai.js: Object contains/includes

Chai has an include method. I want to test to see if an object contains another object. For example:

var origin = {
  name: "John",
  otherObj: {
    title: "Example"
  }
}

I want to use Chai to test if this object contains the following (which it does)

var match = {
  otherObj: {
    title: "Example"
  }
}

Doing this does not appear to work:

origin.should.include(match)

Source: (StackOverflow)

Chai: expecting an error or no depending on the parameter

I've been trying to do a text of a function that handles errors in a way that, if it is a valid error, it is thrown, but if it is not, then nothing is thrown. The problem is that i cant seem to set the parameter while using:

expect(handleError).to.throw(Error);

The ideal would be to use:

expect(handleError(validError)).to.throw(Error);

Is there any way to achieve this functionality?

code of the function:

function handleError (err) {
    if (err !== true) {
        switch (err) {
            case xxx:
            ...
        }
        throw "stop js execution";
    else {}
}

And the code of the test (not working as intended):

it("should stop Javascript execution if the parameter isnt \"true\"", function() {
    expect(handleError).to.be.a("function");
    expect(handleError(true)).to.not.throw(Error);
    expect(handleError("anything else")).to.throw(Error);
});

Source: (StackOverflow)

How can I check that two objects have the same set of property names?

I am using node, mocha, and chai for my application. I want to test that my returned results data property is the same "type of object" as one of my model objects. (Very similiar to chai's instanceof). I just want to confirm that the two objects have the same sets of property names. I am specifically not interested in the actual values of the properties.

Lets say I have the model Person like below. I want to check that my results.data has all the same properties as the expected model does. So in this case, Person which has a firstName and lastName.

So if results.data.lastName and results.data.firstName both exist, then it should return true. If either one doesn't exist, it should return false. A bonus would be if results.data has any additional properties like results.data.surname, then it would return false because surname doesn't exist in Person.

the model

function Person(data) {
  var self = this;
  self.firstName = "unknown";
  self.lastName = "unknown";

  if (typeof data != "undefined") {
     self.firstName = data.firstName;
     self.lastName = data.lastName;
  }
}

Source: (StackOverflow)

How to get "should.be.false" syntax pass jslint?

I am writing JS UT for my NodeJS code. I am using Chai as the assertion library, and I prefer the should syntax. I also use jslint to check the JS file syntax, even the JS files for UT.

Now I have a problem with jslint and Chai. In Chai, you can use:

myvalue.should.be.true;

But jslint give me:

#1 Expected an assignment or function call and instead saw an expression.

I know jslint comes with many options, but I just cannot find the right one to turn off this check.


Source: (StackOverflow)

Equivalent to rspec =~ for arrays in Chai

Does Chai, matchers have an equilivent to rspecs =~ (which means has all elements but order doesn't matter.

Passing example

[1, 2, 3].should =~ [2, 1, 3]

Failing

[1, 2, 3].should =~ [1, 2]

Source: (StackOverflow)

Mocha, Chai: Assert that Object is included in an Array of Objects

Chai has a nice way to assert if an Array includes a certain element

expect([1,2,3]).to.include(2);

What I would like is something similar, given an Array of Objects:

expect([{a:1},{b:2}]).to.include({b:2});

Is this possible?


Source: (StackOverflow)

Assertions library for node.js?

Assertions provided by node.js assert for unit-testing are very limited. Even before I've written the first test I was already creating a few of assertions as it was clear I will keep re-using them.

Could you recommend some good library of assertions to test for common javascript situations (object structures, objects classes, etc., etc.)?

Ideally it should integrate well with nodeunit (or, better, extend it's assertions) - my assertions do not, I have to pass them test as an extra variable...

The only one I've seen is Chai. What could you say about it?


Source: (StackOverflow)