自执行匿名函数,Angular和Jasmine

时间:2015-04-08 09:32:02

标签: angularjs jasmine

在Angular app中给出了这个:

(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])
  })();

哪种测试组功能的最佳(或可能)方式?我应该重构整个方法吗?

THX!

1 个答案:

答案 0 :(得分:0)

首先,您需要将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(/* ... */)
    })
})