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

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

问题:当我尝试模拟SignatureService.getSignatureData时,SpyOn无法按我预期的方式工作,并且表现得好像我是通过callThrough调用茉莉花的getSignatureData方法一样。

我在其他指令和服务中一直使用spyOn和嘲笑,而这些都没有问题。

与其他解决方案和用户的回答相比,最近两天我一直在尝试解决此问题,但是我找不到有效的解决方案。

这是我的代码:

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


茉莉花测试代码:

'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会按我的预期模拟该方法。

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

最佳答案

好吧……我意识到问题在于,首先要创建控制器,而在模拟服务时,控制器会忽略它。
当我将服务的spyOn粘贴到全局beforeEach中时,这个想法是偶然产生的。

因此,我决定创建一个控制器的新实例以及相应的spyOn,并在每个describe的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

        });
    });
});


感谢您的时间。

关于javascript - Jasmine spyOn无法在AngularJS指令上正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49646330/

10-09 09:06