gpt4 book ai didi

javascript - 在我的情况下如何修复这个单元测试?

转载 作者:行者123 更新时间:2023-12-03 08:38:13 25 4
gpt4 key购买 nike

我正在尝试为我的指令进行单元测试。

我有类似的东西

'use strict';
describe('directive test', function () {
var $compile, $rootScope, httpBackend, ngFactory;

beforeEach(module('myApp'));

beforeEach(inject(function (_$compile_, _$rootScope_, _$httpBackend_, _ngFactory_) {
$compile = _$compile_;
scope = _$rootScope_.$new();
$httpBackend = _$httpBackend_;
ngFactory = _ngFactory_;

$httpBackend.whenGET('template.html').respond(200);
}));

it('this will setup directive', function() {
var elem = $compile('<my-factory factoryName="name1"></my-factory>')(scope);
scope.$digest();
expect(scope.run).toBe(1);
});
});

我的指令

(function(window, angular) {
'use strict';
var app = angular.module('myApp');
app.directive('myFactory', ['ngFactory',
function(ngFactory) {
return {
restrict: 'E',
templateUrl:'template.html',
link: function(scope, elem, attrs) { //not cover
scope.test = function() { //not cover
//do stuff here //not cover
}; //not cover
} //not cover
};
}
]);
})(window, angular);

由于某种原因,我的单元测试没有涵盖链接功能。我不确定我做错了什么。有人可以帮我吗?谢谢!

最佳答案

您还需要刷新模板请求:

it('this will setup directive', function() { 
var elem = $compile('<my-factory factoryName="name1"></my-factory>')(scope);
$httpBackend.flush();
scope.$digest();
expect(scope.run).toBe(1);
});

确保加载并呈现正确的模板。

关于javascript - 在我的情况下如何修复这个单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33132823/

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