gpt4 book ai didi

angularjs - 如何测试使用 templateUrl 和 Controller 的指令?

转载 作者:行者123 更新时间:2023-12-04 18:09:45 25 4
gpt4 key购买 nike

编辑:在提出问题后,我现在正在编辑它以详细说明我的发现。

我的应用程序是使用指令模块化的。我正在编写我的指令,以便它们 (1) 创建自己的范围 (2) 使用 templateUrl,以及 (3) 在其 Controller 中执行大部分逻辑和服务器数据获取。

问题是如何使用 Mocha 和 Karma 对其进行单元测试。

最佳答案

为每个指令编写一个测试。由于指令使用了templateUrl,所以我使用了html2js。 html 键应作为模块包含 - 将模板放入 templateCache。

然后,我编译了指令,并使用 rootScope 运行链接函数。我在获取模板 html 时遇到问题 - 使用 $digest 解决。有数据绑定(bind)问题,通过理解解决。所有记录在下面。

下面的代码,

指示:

 angular.module('myApp')
.directive('productThumb', function(){
return {
restrict: 'AE',
scope: true,
templateUrl: 'partials/directives/product-thumb.html',
// controller does most of the work
controller: ProductThumbController

}
}) ;

describe("Unit: Testing Directives", function() {
var elm, scope, linkFn;
beforeEach(
module('ogApp','partials/directives/product-thumb.html') // puts product-thumb.html
// into templateCache
);


beforeEach(inject(function($rootScope, $compile) {
elm = angular.element('<product-thumb></product-thumb>');
scope = $rootScope;
linkFn = $compile(elm);
scope.$digest(); // have to digest to bring html from templateCache
console.log('post compile',elm.html());// <== the html here still have {{}}
}));

it('should show a thumb',function() {
inject(function($controller) {
linkFn(scope); // <== this will create a new scope (since our directive creates
// new scope), runs the controller with it, and bind
// the element to that new scope
scope.$digest();
console.log('post link',elm.html());// <== the html is bound

// inject test data (controller sets up an $on handler for addProductData event)
scope.$broadcast('addProductData',{title:"TEST DISPLAY NAME",
productId: "123", mainImageUrl: "TEST.JPG"});
scope.$digest();
expect(elm.find('H5').text()).to.equal("TEST DISPLAY NAME"); // <=== success
});
});

关于angularjs - 如何测试使用 templateUrl 和 Controller 的指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17223850/

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