如何在单元测试中改变常量值?

时间:2015-04-14 02:43:23

标签: angularjs unit-testing jasmine karma-jasmine

我有一个单元测试,如下所示:

describe('my test', function() {
    var rootScope, $compile, mConfig;

    beforeEach(function() {
        module('app');

        module(function($provide) {
            $provide.value('MyConfig', {myvalue:"first"});
        });

        inject(function($rootScope, _$compile_,MyConfig) {
            rootScope = $rootScope;
            $compile = _$compile_;
            mConfig = MyConfig;
        });
    });

    it('test contant value', function() {
        mConfig.myvalue = "first";
        var scope = rootScope.$new();
        var element = angular.element('<div my-directive></div>');
        element = $compile(element)(scope);

        // when mConfig.myvalue = "first"
        expect($scope.value).toBe("one");

        // when mConfig.myvalue = "second"
        expect($scope.value).toBe("two");

        // when mConfig.myvalue = "thrid"
        expect($scope.value).toBe("three");

    });
});

如何在进行测试的过程中更改常量值?

1 个答案:

答案 0 :(得分:0)

不确定但是如果你的指令依赖于初始的Config值,那么你可以尝试多次创建指令并断言

it('test contant value', function() {
        mConfig.myvalue = "first";
        var scope = rootScope.$new();
        var element = angular.element('<div my-directive></div>');
        element = $compile(element)(scope);

        // when mConfig.myvalue = "first"
        expect($scope.value).toBe("one");

        mConfig.myvalue = "second";
        var scope = rootScope.$new();
        element = angular.element('<div my-directive></div>');
        element = $compile(element)(scope);
        // when mConfig.myvalue = "second"
        expect($scope.value).toBe("two");

        mConfig.myvalue = "third";
        var scope = rootScope.$new();
        element = angular.element('<div my-directive></div>');
        element = $compile(element)(scope);
        // when mConfig.myvalue = "thrid"
        expect($scope.value).toBe("three");

    });