测试在错误时将属性更改为img元素的指令

时间:2014-10-26 22:24:17

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

测试:

'use strict';

describe('Directive: avatar', function () {

  // load the directive's module
  beforeEach(module('app'));

  var element,
    scope,
    avatar_conf,
    timeout,
    mocked_avatar = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';

  beforeEach(inject(function ($rootScope, _$timeout_, _avatar_conf_) {
    scope = $rootScope.$new();
    avatar_conf = _avatar_conf_;
    timeout = _$timeout_;
  }));

  it('should set default alt property for an avatar that cannot be loaded', inject(function ($compile) {
    element = angular.element('<img avatar src="mock.jpg">');
    element = $compile(element)(scope);
    scope.$digest();
    expect(element.attr('alt')).toBe(avatar_conf.default_alt);
  }));

代码:

!(function (window, angular) {
    'use strict';

    /**
     * @ngdoc directive
     * @name app.directive:social
     * @description
     * # social
     */
    angular.module('app.directives')
        .directive('avatar', function(avatar_conf) {
            return {
                restrict: 'A',
                link: function(scope, element, attrs) {
                    element.bind('error', function() {
                        if(!scope.$$phase){
                            scope.$apply(function(){
                                attrs.$set('src', avatar_conf.default_image);
                                attrs.$set('alt', avatar_conf.default_alt);
                            });
                        }

                    });
                }
            };
        });
}(window, window.angular));

问题:断言总是在链接器有机会更改attrs之前发生。 将断言置于超时0之内会导致它完全被调用(在加载DOM之后用于进行断言的hack)。

1 个答案:

答案 0 :(得分:1)

解决方案是升级到Jasmine 2.0并定义异步测试:

升级Jasminekarma-jasmineand grunt-jasmine

$ npm install jasmine --save-dev
$ npm install karma-jasmine --save-dev
$ npm install grunt-jasmine --save-dev

试验:

  it('should set default alt property for an avatar that cannot be loaded', function(done){
    element = angular.element('<img avatar src="mock.jpg">');
    element = $compile(element)(scope);
    scope.$digest();

    setTimeout(function(){
        expect(element.attr('alt')).toBe(avatar_conf.default_alt);
        done();
    }, 200);

  });
相关问题