自执行匿名函数,Angular 和 Jasmine

Self-executing anonymous function, Angular and Jasmine

鉴于此在 Angular 应用中:

(function () {
 "use strict";

function Group(parent, children) {
    function getChildren() {
        return children.map(function (child) {
            if (child.item !== "") {
                return child.item;
            }
        });
    }

    return [parent, getChildren()];
}

function addGroupCtrl($scope) {
    $scope.save = function () {
        var name = "some name";
        var children = [{item:"child1"}]
        console.log(new Group(name, children)
        <!-- some POST request -->
     }

}

angular.module("addGroup", [])
    .controller("addGroupCtrl", ["$scope", addGroupCtrl])
  })();

测试群组功能的最佳(或可能)方法是什么?。我应该重构整个方法吗?

谢谢!

首先,您需要注册Group工厂:

(function () {

 "use strict";

function Group(parent, children) {
    function getChildren() {
        return children.map(function (child) {
            if (child.item !== "") {
                return child.item;
            }
        });
    }

    return [parent, getChildren()];
}

function addGroupCtrl($scope, Group) {
    $scope.save = function () {
        var name = "some name";
        var children = [{item:"child1"}]
        console.log(new Group(name, children)
        <!-- some POST request -->
     }
}

angular.module("addGroup", [])
    .factory('Group', [function() { return Group }])
    .controller("addGroupCtrl", ["$scope", addGroupCtrl])

})();

然后你可以这样测试:

describe('Group', function() {
    var group, Group

    beforeEach(inject(function(_Group_) {
        Group = _Group_
        group = new Group("some name", [{item:"child1"}])
    }))

    it('do something', function() {
        expect(group).to(/* ... */)
    })
})