/chai-angular

Easier testing of Angular apps with Chai.

Primary LanguageJavaScriptMIT LicenseMIT

chai-angular Build Status Coverage Status npm

chai-angular is a collection of small utilities that help testing Angular apps with Chai.

Calling it a collection is a strong word, since it only contains one utility. Hopefully it will stay that way — the more things work out of the box between Angular and Chai, the better!

resourceEql

resourceEql compares Angular resources with plain objects.

Let's say the Angular controller mycontroller contains this code:

var User = $resource('/user/:id');
$scope.user = User.get({id: 9});

A typical test for this controller would be:

var $scope = {};

$httpBackend.expectGET('/user/9').respond({id: '9', name: 'Roger Zelazny'});
$controller('mycontroller', {$scope: $scope});
$httpBackend.flush();

$scope.user.should.deep.equal({id: '9', name: 'Roger Zelazny'});

However, this test fails because $scope.user is not a plain old Javascript object, but an Angular resource, and Chai's deep equality sees them as different.

To make the test pass, install the chai-angular plugin, then replace deep.equal with deep.resource.equal:

$scope.user.should.deep.resource.equal({id: '9', name: 'Roger Zelazny'});

The usual Chai syntactic variants are also available:

$scope.user.should.resourceEql({id: '9', name: 'Roger Zelazny'});

expect($scope.user).to.deep.resource.equal({id: '9', name: 'Roger Zelazny'});
expect($scope.user).to.resourceEql({id: '9', name: 'Roger Zelazny'});

assert.resourceEqual($scope.user, {id: '9', name: 'Roger Zelazny'});
assert.notResourceEqual($scope.user, {id: '10', name: 'Philip K. Dick'});

Installation

$ npm install chai-angular --save-dev

Usage with Karma

In karma.conf.js, add to files the path to chai-angular.js:

module.exports = function(config) {
    config.set({
        basePath : '../',
        files : [
            'node_modules/chai-angular/chai-angular.js',
            ...
        ],
        ...
    });
};

You can then immediately start using chai-angular assertions in your tests.