Подтвердить что ты не робот

Как мы можем протестировать методы управления немасштабированием angular?

У нас есть несколько методов в контроллере Angular, которые не входят в переменную области видимости.

Кто-нибудь знает, как мы можем выполнить или вызвать эти методы внутри теста жасмина?

Вот основной код.

var testController = TestModule.controller('testController', function($scope, testService)
{

function handleSuccessOfAPI(data) {
    if (angular.isObject(data))
    {
       $scope.testData = data;
    }
}

function handleFailureOfAPI(status) {
    console.log("handleFailureOfAPIexecuted :: status :: "+status);
}

 // this is controller initialize function.
 function init() {
    $scope.testData = null; 

    // partial URL
    $scope.strPartialTestURL = "partials/testView.html;

    // send test http request 
    testService.getTestDataFromServer('testURI', handleSuccessOfAPI, handleFailureOfAPI);
}

 init();
}

Теперь в моем тесте jasmine мы передаем метод handleSuccessOfAPI и handleFailureOfAPI, но это undefined.

Вот тестовый код жасмина.

describe('Unit Test :: Test Controller', function() {
var scope;
var testController;

var httpBackend;
var testService;


beforeEach( function() {
    module('test-angular-angular');

    inject(function($httpBackend, _testService_, $controller, $rootScope) {

        httpBackend = $httpBackend;
        testService= _testService_;

        scope = $rootScope.$new();
        testController= $controller('testController', { $scope: scope, testService: testService});
            });
});

afterEach(function() {
       httpBackend.verifyNoOutstandingExpectation();
       httpBackend.verifyNoOutstandingRequest();
    });

it('Test controller data', function (){ 
    var URL = 'test server url';

    // set up some data for the http call to return and test later.
    var returnData = { excited: true };

    // create expectation
    httpBackend.expectGET(URL ).respond(200, returnData);

    // make the call.
    testService.getTestDataFromServer(URL , handleSuccessOfAPI, handleFailureOfAPI);

    $scope.$apply(function() {
        $scope.runTest();
    });

    // flush the backend to "execute" the request to do the expectedGET assertion.
    httpBackend.flush();

    // check the result. 
    // (after Angular 1.2.5: be sure to use `toEqual` and not `toBe`
    // as the object will be a copy and not the same instance.)
    expect(scope.testData ).not.toBe(null);
});
});
4b9b3361

Ответ 1

Как и у вас не будет доступа к этим функциям. Когда вы определяете именованную функцию JS, она так же, как если бы вы говорили

var handleSuccessOfAPI = function(){};

В этом случае было бы довольно ясно видеть, что var находится только в области внутри блока, и внешняя ссылка на него отсутствует с контроллера упаковки.

Любая функция, которая может быть вызвана дискретно (и, следовательно, проверена), будет доступна в $scope контроллера.

Ответ 2

Я знаю, что это старый случай, но вот решение, которое я использую.

Используйте 'this' вашего контроллера

.controller('newController',['$scope',function($scope){
    var $this = this;
    $this.testMe = function(val){
        $scope.myVal = parseInt(val)+1;
    }
}]);

Вот тест:

describe('newDir', function(){
var svc, 
    $rootScope,
    $scope,
    $controller,
    ctrl;


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

 beforeEach(function () {
    inject(function ( _$controller_,_$rootScope_) {

        $controller = _$controller_;
        $rootScope = _$rootScope_;
        $compile = _$compile_;
        $scope = $rootScope.$new();
        ctrl = $controller('newController', {'$rootScope': $rootScope, '$scope': $scope });
    });
});

it('testMe inc number', function() {

    ctrl.testMe(10)
    expect($scope.myVal).toEqual(11);
});

});

Полный пример кода