Unit Test Expect SpyOn Not Found

為{幸葍}努か 提交于 2020-01-02 13:30:14

问题


I have a directive (restrict A) that handles an event click, and calls a service based on a value.

Directive:

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

Test:

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(function (_$rootScope_, _$compile_, _myFactory_) {
        scope = _$rootScope_.$new();
        $compile = _$compile_;
        var html = '<div><a my-directive  value="\'red\'"></a></div>';
        myFactory = _myFactory_;
        spyOn(myFactory , 'red').and.callThrough();
        element = $compile(angular.element(html))(scope);
        scope.$digest();

    }));

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

With the above, i get error:

Expected spy red to have been called.

Im using Jasmine 2


回答1:


You are clicking the <div>, not the <a>, which has the directive and the event handler. Do:

element.find('a').click();

Or simply remove the <div> from the compiled HTML.



来源:https://stackoverflow.com/questions/35654818/unit-test-expect-spyon-not-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!