【问题标题】:Unable to unit test scopes inside a function无法对函数内的范围进行单元测试
【发布时间】:2014-11-20 12:06:38
【问题描述】:

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

Ctrl:

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。

任何帮助将不胜感激。

【问题讨论】:

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


    【解决方案1】:

    你忘记打电话了

    scope.address()  
    

    测试里面的函数。如果不调用这个函数,

    $scope.addressValue
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-13
      • 2013-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-15
      • 1970-01-01
      • 2014-01-15
      相关资源
      最近更新 更多