vendredi 26 février 2016

Unit Test Directive Click Event Based On Scope Value

I have a directive attribute, that passes a value and performs an action based on the 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>

Unit Test:

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

Aucun commentaire:

Enregistrer un commentaire