一尘不染

我们如何测试非作用域角度控制器方法?

angularjs

Angular Controller中的方法很少,它们不在scope变量上。

有谁知道,我们如何在Jasmine测试中执行或调用这些方法?

这是主要代码。

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();
}

现在,在我的茉莉花测试中,我们正在传递“ handleSuccessOfAPI”和“ handleFailureOfAPI”方法,但是这些是未定义的。

这是茉莉花测试代码。

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);
});
});

阅读 158

收藏
2020-07-04

共1个答案

一尘不染

因为您将无法使用这些功能。当您定义一个命名的JS函数时,就像您要说的一样

var handleSuccessOfAPI = function(){};

在这种情况下,可以很清楚地看到var仅在块内的范围内,并且包装控制器没有外部引用。

可以离散调用(因此已测试)的任何功能将在控制器的$ scope上可用。

2020-07-04