如何测试promis中包含的函数

时间:2016-02-03 17:12:28

标签: javascript angularjs karma-jasmine

我的ctrl是这样的:

(function() {
'use strict';

angular
    .module('App')
    .controller('DeviceStatesCtrl', DeviceStatesCtrl);

function DeviceStatesCtrl( $rootScope, $scope, $translate,DeviceStatesService) {
    var vm = this;
    DeviceStatesService.getObject().then(function(response){
        vm.init(response);
    });
    vm.init= function(response){
        $translate(['table.title']).then(function(translate){
             some stuff here
        }));
    }
}})();

我的茉莉花测试是这样的:

describe('app module', function() {
//var controller = null;
var $controller, $translate,$compile,createController,DeviceStatesService,$translate, scope;
var mockInit= sth;

beforeEach(function () {
    module('App');
});

// Provide will help us create fake implementations for our dependencies, do not useful
module(function($provide) {

    // Fake StoreService Implementation returning a promise
    //nothing works :(
    $provide.value('DeviceStatesService', {
        getStatesObject: function() {
            return {
                then: function(callback) {
                    return callback([{ some: "thing", hoursInfo: {isOpen: true}}]);
                }
            };
        }
    });

    });

    return null;
});

beforeEach(inject(function($controller,$rootScope, _$translate_, _DeviceStatesService_) {
    scope = $rootScope.$new();

    //for 'controller as' syntax
    $controller('DeviceStatesCtrl as deviceStat', {
        $scope: scope
    });

    createController = function(params) {
        return $controller("DeviceStatesCtrl as deviceStat", {
            $scope: scope,
            $stateParams: params || {}
        });
    };
}));

describe("Unit:Device States controller", function() { 
    //test init function
    it("init function get called correctly", function() {

        //spyOn(DeviceStatesService, 'getStatesObject').and.callThrough();
        //createController();
        //expect(DeviceStatesService.getStatesObject).toHaveBeenCalled();

        expect(scope.deviceStat.init).toBeDefined();
        //in init, all things are warpped in the $translate
        //spyOn(scope.deviceStat, 'init');

        scope.deviceStat.init(mockInit);
        scope.deviceStat.setChart('All');

        //expect(scope.deviceStat.totalNum).toEqual(22);
    });
});
});

我的问题是如何测试init函数及其中的内容? init函数是一个promise,我不知道如何调用它。作为我的代码scope.deviceStat.init(mockInit),它不起作用。另一个问题是$ translate承诺,如何在其中传递参数?

1 个答案:

答案 0 :(得分:0)

您使用done函数,这是通过jasmine函数传递给规范的参数..示例..

describe("My Test set", function() {
  it("My Test", function(done) {
    doAsync().then(function(result) {
      done();
    }).catch(function(err) {
      fail();
    }
  }
}

希望这有帮助。