基于范围值的单元测试指令点击事件

Unit Test Directive Click Event Based On Scope Value

我有一个指令属性,它传递一个值并根据该值执行操作:

define(function () {
'use strict';

var myDirective = function ($rootScope, myFactory) {
    return {
        restrict: 'A',
        scope: {
            _myValue : '=value'
        },
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                if (scope._myValue === 'red') {
                    myFactory.red();
                }
                if (scope._myValue === 'green') {
                    myFactory.green();
                }
                if (scope._myValue === 'black') {
                    myFactory.black();
                }
            });
        }
    };
};

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

HTML:

<a my-directive  value="\'red\'"></a>

单元测试:

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

var angular = require('angular');

describe('<-- Directive Spec ------>', function () {

    var scope, $compile, element;

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

    beforeEach(inject(['$rootScope', '$compile', function (_$rootScope_, _$compile_) {
        scope = _$rootScope_.$new();
        $compile = _$compile_;

        var html = '<a my-directive  value="\'red\'"></a>';
        element = $compile(angular.element(html))(scope);
        scope.$digest();

    }]));

    it('should be red and call myFactory.red', function () {
        element.click();
    });

更新:

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

var angular = require('angular');

describe('<-- Directive Spec ------>', function () {

    var scope, $compile, element, myFactory;

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

    beforeEach(inject(['$rootScope', '$compile', function (_$rootScope_, _$compile_, _myFactory_) {
        scope = _$rootScope_.$new();
        $compile = _$compile_;

        var html = '<a my-directive  value="\'red\'"></a>';
        myFactory = _myFactory_;
        spyOn(myFactory , 'red');
        element = $compile(angular.element(html))(scope);
        scope.$digest();

    }]));

    it('should be red and call myFactory.red', function () {
        expect(myFactory.red).toHaveBeenCalled();
    });

尝试了上面的方法并得到错误:

Error: spyOn could not find an object to spy upon for red()

工厂示例:

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

    var myFactory = function () {    

        return {
            red: function() {
                console.log('red');
            },
            green: function() {
                console.log('green');
            },
            black: function() {
                console.log('black');
            }
        };
    };

    return myFactory;
});

我会在 beforeEach 中添加一个像这样的间谍:

spyOn(myFactory, 'red');

然后检查它是否被调用:

expect(myFactory.red).toHaveBeenCalled();

当然要注入myFactory.