简体   繁体   English

参考错误找不到变量$ compile

[英]Reference error can't find variable $compile

I am unit testing an AngularJS directive with Jasmine. 我正在用Jasmine对AngularJS指令进行单元测试。

I am getting this error even though I injected $compile in a beforeEach statement: 即使在beforeEach语句中注入了$compile ,我仍然收到此错误:

Reference Error: can't find variable: $compile

describe('test', function() {
    beforeEach(inject(function(_$compile_, _$rootScope_) {
        $compile = _$compile_;
        $rootScope = _$rootScope_;
    }));

    describe('testCase', function() {
        var nlElement = angular.element('<div directive></div>');
        var element = $compile(nlElement)($rootScope); // this is where the error is being thrown
        $rootScope.$digest();

        it(...)
    });
});

Do I have to include the statements in the second describe in the it blocks? 我是否必须将第二个describe中的语句包括在it块中? Ultimately I want to be able to inject all three of those statements before each test, but I am trying to resolve the $compile error at the moment. 最终,我希望能够在每次测试之前注入所有这三个语句,但是我现在正在尝试解决$compile错误。

It turns out that the describe blocks are executed before the beforeEach statements, which is counter-intuitive to me. 事实证明, describe块是在beforeEach语句之前执行的,这与我的直觉相反。 Also, if you want to initialize variables and your directive before your tests (like I did in the second describe block, then include it in a beforeEach statement, and test your assertions in it blocks. 另外,如果您想在测试之前初始化变量和指令(如我在第二个describe块中所做的那样,则将其包含在beforeEach语句中,然后在it块中测试断言。

describe('test', function() {


    describe('testCase', function() {
        beforeEach(inject(function(_$compile_, _$rootScope_) {
            $compile = _$compile_;
            $rootScope = _$rootScope_;
        }));

        beforeEach(inject(function() {    
            var nlElement = angular.element('<div directive></div>');
            var element = $compile(nlElement)($rootScope); // this is where the error is being thrown
            $rootScope.$digest();
        }));

        it(...)
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM