gpt4 book ai didi

AngularJS Karma Jasmine 测试指令因 $compile 而失败?

转载 作者:行者123 更新时间:2023-12-02 03:22:55 24 4
gpt4 key购买 nike

我正在使用 Jasmine 为 angularJS 中的指令编写测试。在 karma.conf.js 中,我包含了所有依赖项和我的模块的路径。我正在使用的指令非常复杂,因此我借用了一些简单的自定义指令代码来进行测试。它在 js fiddle 和我的应用程序中的指令函数中运行良好,但在我的应用程序中未通过以下测试:

我的规范看起来像这样:

describe('Unit testing: ', function() {
var $compile,
$rootScope;

beforeEach(module('app.directives')); // our directives

// Store references to $rootScope and $compile
// so they are available to all tests in this describe block
beforeEach(inject(function(_$compile_, _$rootScope_){
// The injector unwraps the underscores (_) from around the parameter names when matching
$compile = _$compile_;
$rootScope = _$rootScope_;
}));

it('Replaces the element with the appropriate content', function() {
// Compile a piece of HTML containing the directive
var element = $compile("<div hello-world></div>")($rootScope);

// fire all the watches, so the scope expression {{1 + 1}} will be evaluated
$rootScope.$digest();

// Check that the compiled element contains the templated content
expect(element.html()).toContain("Hello World!");
});
});

指令看起来像这样:

angular.module('app.directives')
.directive('helloWorld', function() {
return {
restrict: 'AE',
template: '<h3>Hello World!!</h3>'
};
});

当我运行 grunt karma 时,最后一个测试失败了,因为:

Firefox 40.0.0 (Mac OS X 10.10.0) Unit testing:  Replaces the element with the appropriate content FAILED
Expected '' to contain 'Hello World!'.

当我插入一些 console.log 语句时,我看到的主要问题是指令在我调用 $compile 之后(或者在 $digest 之后)没有正确编译:

Firefox 40.0.0 (Mac OS X 10.10.0) LOG: {0: <div class="ng-scope" hello-world=""></div>, length: 1}

我很困惑。我知道我可能需要提供更多关于我的申请的信息,但简而言之,这个解释是我的核心问题。

[edit]:创建一个新模块是对此的快速修复,但问题仍然是当单个模块中有多个指令(仍然失败)时如何处理指令单元测试。

最佳答案

(答案已编辑)一旦我确定它已正确包含在我的 karma.conf.js 中,您的代码就对我有用。

files: [
"include/path/to/your/directive/file.js",
"include/path/to/your/directive/test.js"
]

关于AngularJS Karma Jasmine 测试指令因 $compile 而失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32083947/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com