如何在Angular中测试$ resource的$ save()

时间:2016-04-01 19:43:31

标签: angularjs jasmine

我有一个只返回$ resource()的服务。它在我的控制器中用于使用$ save()发出POST请求。我在为Controller编写Jasmine测试时面临问题> SettingAdd()。我无法为服务设置正确的模拟,因为我的测试失败了。以下是我的代码:

注意:根据我的分析,伪造的$ save()方法未正确调用,因此测试失败

我的服务:

angular
    .module('App')
    .factory('Setting', setting)
    .$inject = ['$resource', 'constants'];

function setting($resource, constants) {
    return $resource(constants.LOCAL_API_BASE_URL + '/api/settings', {}, {
        query: { method: 'GET', params: {}, isArray: true, ignoreLoadingBar: true }
    });
}

我的控制器:

angular
    .module('App')
    .controller('SettingAddController', SettingAdd)
    .$inject = ['$q','Setting'];

function SettingAdd($q,Setting) {
    var vm = this;
    vm.setting = new Setting(); 
    vm.addSetting = addSetting;

    function addSetting() {

        vm.setting
            .$save()
            .then(function successCallback(response) {
                vm.operationMsg.success = true;

            }, function errorCallback(response) {
                vm.operationMsg.success = false;
            })
        .finally(function () {
        });
    }
}

我的茉莉花测试:

describe("SettingAddController controller", function () {
    var scope,
        ctlr,
        SettingService;

    beforeEach(module('App'));

    beforeEach(inject(function ($rootScope, $controller, $q, Setting) {
        scope = $rootScope.$new();

        SettingService = Setting;

        var settingAddDeferred = $q.defer();

        spyOn(Setting.prototype, '$save').and.callFake(function () {
            return settingAddDeferred.promise;
        });


        ctlr = $controller('SettingAddController');

        settingAddDeferred.resolve({ msg: 'Success' });

        $rootScope.$apply();
    }));


    it("should make a POST request to setting API if form is valid when Save is clicked", function () {
        ctlr.addSetting();
        expect(ctlr.operationMsg.success).toBe(true);
    });
});

1 个答案:

答案 0 :(得分:3)

在您的控制器中,您不会公开方法addSetting()以及您在测试中无法使用的此方法。首先你应该:

vm.addSetting = addSetting;

在您的规范中,在该方法之后,您应该使用范围。$ digest()(或$ apply),不要之前。

describe("SettingAddController controller", function () {
    var scope,
        ctlr,
        SettingService,
        settingAddDefer;

    beforeEach(module('App'));

    beforeEach(inject(function ($rootScope, $controller, $q, Setting) {
        scope = $rootScope.$new();

        SettingService = Setting;

        settingAddDeferred = $q.defer();

        spyOn(Setting.prototype, '$save').and.callFake(function () {
            return settingAddDeferred.promise;
        });


        ctlr = $controller('SettingAddController');

    }));


    it("should make a POST request to setting API if form is valid when Save is clicked", function () {
        ctlr.addSetting();
        settingAddDeferred.resolve({ msg: 'Success' });
        $rootScope.$apply();
        expect(ctlr.operationMsg.success).toBe(true);
    });
});