无法在函数内单元测试范围

时间:2014-11-20 12:06:39

标签: javascript angularjs unit-testing angularjs-scope karma-runner

我第一次尝试为我的代码编写单元测试。我可以在我的控制器顶部声明时测试$ scopes,但是我如何测试$ scope函数内的$ scope?

控制:

app.controller("MyCtrl", function($scope, $http, myService) {
    $scope.initialiseValue = 0;

    $scope.address = function (value) {

        $scope.addressValue = 0;

    }
});

测试:

describe('app', function () {

    var app;
    beforeEach(function () {
        app = angular.mock.module('app')
    });

    describe('MyCtrl', function () {
        var scope, ctrl, theService , httpMock;

        beforeEach(inject(function($controller, $rootScope, myService, $httpBackend) {
            scope = $rootScope.$new(),
            ctrl = $controller('MyCtrl', {
                $scope: scope,
                $location : location,
                myService: theService ,
                $httpBackend: httpMock
            });
        }));

    // This test succeeds ///////////

    it('initialiseValue should be initialised to 0', function() {
        console.log(scope.initialiseValue );
        expect(scope.initialiseValue ).toBe(0);
    });

    // This test fails ///////////
    it('addressValue should be initialised to 0', function() {
        console.log(scope.addressValue );
        expect(scope.addressValue ).toBe(0);
    });

});

错误:

Expected undefined to be false.

使用Karma和Jasmine。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

你忘了打电话了

scope.address()  

测试中的功能。如果您不调用此功能,

$scope.addressValue

无法更新。更新了工作小提琴http://jsfiddle.net/themyth92/j3pkaebw/1/

相关问题