角度单元测试 - 控制器中的模拟方法

时间:2015-12-31 10:45:13

标签: angularjs unit-testing jasmine karma-jasmine

我需要在控制器中模拟服务方法。我知道如何模拟像service.method这样的简单服务,但不喜欢这个。我不知道如何模拟" action.user.update"。如果我试图窥探它,我收到一个错误'无法阅读财产'更新'未定义'。

JsFidleDemo

我的服务:

.service('action', ['$http', '$q', function ($http, $q) {
    var service = {};

     service.user = {
        update: function (data, config) {
             return service.run({
                name: config.name,
                call: $http({
                    method: "POST",
                    url: "/user/edit",
                    data: data
                }),
                success: config.success,
                error: config.error
            });
        }
    };

    return service;
}]);

1 个答案:

答案 0 :(得分:0)

你有一半

$provide.value('action', action);

其中action应该是您在单元测试中创建的对象

action = {
    user: {
        update: jasmine.createSpy('action.user.update')
    }
}
$provide.value('action', action);

然后在测试中

scope.saveUser()
expect(action.user.update).toHaveBeenCalled()

更新了小提琴 http://jsfiddle.net/3oavnmev/1/