How do I test AngularJS code using Mocha?

前端 未结 2 1466
无人共我
无人共我 2021-02-05 03:25

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

2条回答
  •  星月不相逢
    2021-02-05 03:56

    If you're creating an angular service that doesn't have any dependencies and isn't necessarily angular specific, you can write your module in an angular-agnostic way, then either write a separate small angular wrapper for it, or test for the presence of angular, and conditionally create a service for it.

    Here's an example of an approach that I use to create modules that can be used both in angular, the browser, and node modules, including for mocha tests:

    (function(global) {
        //define your reusable component
        var Cheeseburger = {};
    
        if (typeof angular != 'undefined') {
            angular.module('Cheeseburger', [])
                .value('Cheeseburger', Cheeseburger);
        }
        //node module
        else if (typeof module != 'undefined' && module.exports) {
            module.exports = Cheeseburger
        }
        //perhaps you'd like to use this with a namespace in the browser
        else if (global.YourAppNamespace) {
            global.YourAppNamespace.Cheeseburger = Cheeseburger
        }
        //or maybe you just want it to be global
        else {
            global.Cheeseburger = Cheeseburger
        }
    })(this);
    

提交回复
热议问题