Jasmine spyOn在AngularJS指令上无法正常工作

时间:2018-04-04 08:34:30

标签: javascript angularjs unit-testing angularjs-directive jasmine

我正在开发一个AngularJS应用程序,我在一个具体的指令中遇到了Jasmine的SpyOn的一些问题。

该指令非常简单,只需调用服务的方法,当它解析/拒绝承诺行为时,设置一些值或其他值。

问题:当我尝试模仿SignatureService.getSignatureData时,SpyOn无法正常工作,就好像我在callThrough上调用jasmine的getSignatureData方法一样}。

我一直在其他指令和服务中使用spyOn和mocks,并且没有问题。

过去两天我一直试图解决这个问题,与其他解决方案和用户的答案相比,但我找不到有效的解决方案。

这是我的代码:

AngularJS指令代码

angular
    .module('module_name')
    .directive('signatureDirective', signatureDirective);

angular
    .module('GenomcareApp_signature')
    .controller('signatureDController', signatureDController);

function signatureDirective() {
    return {
        restrict: 'E',
        templateUrl: 'components/signature/signature.directive.html',
        controller: signatureDController,
        controllerAs: 'ctrl',
        bindToController: true
    };
}

signatureDController.$inject = [
    '$scope',
    '$rootScope',
    '$location',
    'SignatureService'
];

function signatureDController($scope, $rootScope, $location, SignatureService) {
    var controller = this;

    $scope.$on('pdfFileLoadSuccessfully', function (data) {
        console.log(data);
        controller.loadPdfSucceed = true;
    });

    $scope.$on('pdfFileLoadFails', function (data) {
        console.error(data);
        controller.loadPdfError = true;
    });

    function loadDirectiveInitData() {
        var  queryParameters = atob($location.search().data);
        controller.email = queryParameters.split(';')[0];
        controller.phone = queryParameters.split(';')[1];
        controller.docid = queryParameters.split(';')[2];

        SignatureService.getSignatureData(controller.email, controller.phone, controller.docid)
            .then(
                function (data) {
                    console.log(data);
                    controller.stampTime = data.stamp_time;
                    controller.fileUrl = data.original_file.url;
                },
                function (error) {
                    console.error(error);
                    controller.error = true
                })
            .finally(
                function () {
                    controller.endLoad = true;
                })
    }

    loadDirectiveInitData();
}

Jasmine测试代码

'use strict';
/* global loadJSONFixtures */


describe('Test :: Signature directive', function () {
    beforeEach(angular.mock.module('app'));
    beforeEach(module('translateNoop'));

    var $q, $compile, $rootScope, controller, $scope, $httpBackend, $location, SignatureService;

    beforeEach(angular.mock.inject(function (_$controller_, _$q_, _$rootScope_, _$location_, _$compile_, _$httpBackend_, _SignatureService_) {
        $q = _$q_;
        $compile = _$compile_;
        $location = _$location_;
        $scope = _$rootScope_.$new();
        $httpBackend = _$httpBackend_;
        SignatureService = _SignatureService_;

        spyOn($location, 'search').and.returnValue({data: 'dGVzdEB0ZXN0LmNvbTsrMzQ2NjY2NjY2NjY7WG9TUFFnSkltTWF2'});
        $httpBackend.whenGET('components/signature/signature.directive.html').respond(200, '');

        controller = _$controller_('signatureDController', {$scope: $scope});
    }));

    describe('Testing directive', function () {
        it('Init data should be set when promise resolves/rejects', function (done) {
            // SpyOn DOES NOT MOCK THE SERVICE METHOD
            spyOn(SignatureService, 'getSignatureData').and.callFake(function () {
                return $q.resolve({...})
            });

            var element = angular.element('<signature-directive></signature-directive>');
            element = $compile(element)($scope);
            $scope.$digest();
            done();

            // ... some expect stuff
        });
    });
});

如果有人能给我一些建议或解决方案,我会非常感激。

非常感谢。

UPDATE1:我不知道为什么,但如果我没有在全局controller中声明beforeEach变量,那么Jasmine的spyOn会按照我的预期嘲笑该方法。

现在问题是如何让控制器测试控制器值是否按预期设置。

2 个答案:

答案 0 :(得分:0)

尝试使用$q.defer(),这是一个例子:

it('Init data should be set when promise resolves/rejects', function (done) {
        // SpyOn DOES NOT MOCK THE SERVICE METHOD
        spyOn(SignatureService, 'getSignatureData').and.callFake(function () {
            let deferred = $q.defer();
            deferred.resolve({...});
            return deferred.promise;
        });

        var element = angular.element('<signature-directive></signature-directive>');
        element = $compile(element)($scope);
        $scope.$digest();
        done();

        // ... some expect stuff
    });

答案 1 :(得分:0)

嗯......我意识到问题在于控制器是在所有人之前创建的,并且在某种程度上当服务被模拟时控制器忽略它。 当我将服务spyOn粘贴到全球beforeEach时,这个想法就出现了。

所以我决定在每个 describe spyOn内创建一个新的控制器实例和相应的beforeEach,并带有所需的结果。

有效。也许它不是最好的方法,我鼓励任何有答案的人发布它。我将永远是伟大的。

这是我的最终测试代码:

describe('Test :: Signature directive', function () {
    beforeEach(angular.mock.module('app'));
    beforeEach(module('translateNoop'));

    var $q, $compile, $rootScope, $scope, $httpBackend, $location, SignatureService, test_fixture;

    beforeEach(angular.mock.inject(function (_$q_, _$rootScope_, _$location_, _$compile_, _$httpBackend_, _SignatureService_) {
        $q = _$q_;
        $compile = _$compile_;
        $location = _$location_;
        $scope = _$rootScope_.$new();
        $httpBackend = _$httpBackend_;
        SignatureService = _SignatureService_;
        // controller = _$controller_;

        spyOn($location, 'search').and.returnValue({data: 'dGVzdEB0ZXN0LmNvbTsrMzQ2NjY2NjY2NjY7WG9TUFFnSkltTWF2'});
        $httpBackend.whenGET('components/signature/signature.directive.html').respond(200, '');
    }));

    describe('Testing directive when service resolve promise', function () {
        var controller;
        beforeEach(inject(function(_$controller_) {
            spyOn(SignatureService, 'getSignatureData').and.callFake(function () {
                return $q.resolve({...})
            });

            controller = _$controller_('signatureDController', {$scope: $scope})
        }));

        it('Init data should be set', function () {
            // spyOn($location, 'search').and.callThrough();
            var element = angular.element('<signature-directive></signature-directive>');
            element = $compile(element)($scope);
            $scope.$digest();

            // ... some expect(...).toEqual(...) stuff and more

        });
    });
});

感谢您的时间。