如果未定义attr,则测试指令抛出异常

时间:2015-09-22 21:39:04

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

我有一个angularjs指令,需要定义资源attr才能生成一些逻辑。接下来是它的最小定义:

angular.module('myAppName')
    .directive('loadObjects', loadObjects);

function loadObjects($window) {
    var directive = {
        restrict: 'E',
        template: '<md-content class="md-whiteframe-z4" layout-padding></md-content>',
        link: function(scope, element, attrs) {
            if (angular.isUndefined(attrs.resource)) {
                throw 'resource attr is mandatory';
            }
        }
    };
    return directive;
}

然后在我的测试中,我试图测试一个无效的模板抛出异常。

describe('LoadObjects directive', function() {
    beforeEach(module('myAppName'));

    it('should throw an error if resource attr is not defined', inject(function($rootScope, $compile) {
        var scope = $rootScope.$new();
        var elem = angular.element('<load-objects></load-objects>');
        expect(function() { $compile(elem)(scope); }).toThrow('resource attr is mandatory');
    }));
});

但是我得到了下一个错误:

Expected function to throw 'resource attr is mandatory', but it threw TypeError: 'undefined' is not an object (evaluating '$window.Raven.captureMessage')

此外,我还尝试在模板中使用该指令,我可以在javascript控制台中看到异常。

欢迎任何建议。谢谢你的阅读。

修改

之后,我试图使用:

beforeEach(module('myAppName', function($provide, $injector) {
    $provide.constant('DEBUG', true);
    console.log($injector.get('DEBUG')); // it prints true
}));

在beforeEach中,DEBUG被更改,但它不起作用。

为了让我的测试成功,我需要DEBUG=true,我的第二个问题:这种方法有什么问题?

1 个答案:

答案 0 :(得分:0)

好的,这是我最后的方法:

正如我所说,如果我配置我的测试将通过:

$ravenProvider.development(DEBUG); // with DEBUG=true

但是从那以后:

beforeEach(module('myAppName', function($provide, $injector) {
    $provide.constant('DEBUG', true);
    console.log($injector.get('DEBUG')); // it prints true
}));

不起作用,我决定直接改变传递给raven的值:

beforeEach(module('myAppName', function($ravenProvider) {
    $ravenProvider.development(true);
}));

现在就可以了。