【问题标题】:Unit Test Directive Method does not exist单元测试指令方法不存在
【发布时间】:2016-03-01 12:00:04
【问题描述】:

我正在尝试测试一个指令:

define(['require'], function (require){
'use strict';

var myDirective = function ($rootScope, MyService) {

    return {
        restrict: 'E',
        templateUrl: 'app/banner/banner.html',
        scope: {},
        controller: [ '$scope', '$element', function ($scope, element) {                

            $scope.sendEmail = function(data) {
                $scope.showConfirmation = false;
                $rootScope.$broadcast('process-email', data);
            };
        }]
    };
};

 return ['$rootScope', 'MyService', myDirective];
});

banner.html

<ul>
    <li><a href="javascript:;" ng-click="sendEmail('process')" class="email-item">Send mail</a></li>
    <li><a href="javascript:;" ng-click="sendEmail('clarify')" class="email-item">Clarify mail</a></li>
</ul>

测试:

define(['require', 'angular-mocks'], function (require) {
    'use strict';

    var angular = require('angular');

    describe('MyDirective Spec ->', function () {

        var scope, $compile, element, $httpBackend;

        beforeEach(angular.mock.module('MyApp'));

        beforeEach(inject(function (_$rootScope_, _$httpBackend_) {
            scope = _$rootScope_.$new();
            $compile = _$compile_;
            $httpBackend = _$httpBackend_;
            var html = '<div my-directive></div>';
            element = $compile(angular.element(html))(scope);
            scope.$digest();
        }));

        it('should test sendEmail', function () {
            spyOn(scope, 'sendEmail').and.callThrough();
            element.find('.email-item').click();
            expect(scope.sendEmail).toHaveBeenCalled();
        });
    });
});

我得到错误:

Error: sendEmail() method does not exist

【问题讨论】:

  • 您的任何测试都通过了吗?
  • 不,他们现在没有

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


【解决方案1】:

你已经为指令指定了scope: {},它有一个独立的范围。它在隔离范围内具有sendEmail 函数。

因此,在单元测试时,为了访问函数,您必须从指令元素中获取隔离范围,如下所示:

var isolateScope = element.isolateScope()
isolateScope.sendEmail() // <- this

如果您需要更多信息,这篇文章可能会有所帮助:http://thejsguy.com/2015/02/12/unit-testing-angular-directives.html

【讨论】:

  • 谢谢,尝试添加: var isolateScope = element.isolateScope();期望(isolateScope.sendEmail).toHaveBeenCalled();仍然看到同样的错误。
  • element.scope() 怎么样
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-18
  • 1970-01-01
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
  • 2018-07-03
相关资源
最近更新 更多