简体   繁体   中英

Set up unit testing with Mocha on an AngularJs app

I'm trying to setup unit testing on my webapp using mocha. My webapp uses AngularJs and since I'm still new to this framework, I'm having a hard time to setup this.

In fact, is there a way to setup this by using nothing else than mocha? I mean, is it possible to setup my unit tests without Karma or any other test runners (and no browser)?

Here's my code to test :

define(['angular'], function (angular) {
var module = angular.module('MyModule', []);

module.controller('MyController', ['$scope', '$window', function ($scope, $window) {
        $scope.test = function () {
            $window.alert('Not implemented yet.');
        };
    }]);

    return module;
});

And here's my test code:

require("chai");
require('../lib/angular/angular-mocks');

describe("Unit testing example", function() {

    beforeEach(angular.mock.module('MyModule'));

    it('should test nothing', function() {
        expect(true).to.be.true;
    })

});

When I try to execute this, I receive this error:

angular.mock = {};
^
ReferenceError: angular is not defined

Thank you for your help!

Yes, you need something that will provide some sort of browser environment for your Angular code. There are multiple options:

  • jsdom .

  • Headless solutions like PhantomJS.

  • Actual browsers.

Each of these solutions provide a browser environment which is progressively closer to the "real thing".

What you need exactly depends on:

  • That minimum AngularJS requires. I don't use AngularJS so I don't know what this minimum is.

  • What minimum your own code requires.

For instance, I've used jsdom for unit tests for code that just navigates up and down the DOM tree. Jsdom was perfect for this. However, when I tried to use jsdom to test code that uses MutationObserver , that did not work because jsdom does not provide this API. I've had to use real browsers to perform these tests.

A word of caution: if you care at all about cross-browser compatibility nothing replaces testing code against actual browsers. Just yesterday I diagnosed a problem that happened only in Safari. There was no way to catch this problem using anything else than Safari to test the offending code.

For those facing this issue with jsdom for testing

Adding the following solve it for me seach for a day

require('mutationobserver-shim')
global.MutationObserver = global.window.MutationObserver

of course you need to npm yarn install mutationobserver-shim

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM