我已经检查了与this Q& A相关的指令隔离范围,这有助于我解决测试使用'@'
属性的属性的问题。但我发现很难测试使用'='
属性的属性。
考虑(从我的指令即将发布):
return {
restrict: 'A',
link: link,
scope: {
upcoming: '@',
patientDetails: '='
}
};
在我对upcoming
的测试中,我可以使用isolateScope()
函数访问它(从角度1.2开始),如下所示:
elm = angular.element('<div upcoming="remembered" patient-details="patientDetails"></div>');
// Compiles the directive and links it to the scope
$compile(elm)(scope);
scope.$digest();
isolateScope = elm.isolateScope();
在测试中我可以这样做:
it("should have attribute 'upcoming' attached to isolate scope", function () {
expect(isolateScope.upcoming).toBeDefined();
expect(isolateScope.upcoming).toBe('remembered');
});
但如果我以同样的方式接近其他属性,我会收到undefined
错误。然后我尝试了这个:
// Retrieve the target html - remembered.html
beforeEach(inject(function ($compile) {
patient = {
name: 'Lorem Ipsum',
readyForRefill: 1,
progressCount: 2,
upcomingCount: 3,
taggedCount: 4,
expiringCount: 5,
oneRefillRemaining: 9000
};
elm = angular.element('<div upcoming="remembered" patient-details="patient"></div>');
// Compiles the directive and links it to the scope
$compile(elm)(scope);
scope.$digest();
isolateScope = elm.isolateScope();
isolateScope.patientDetails = patient;
}));
测试:
it("should have attribute 'patientDetails' attached to isolate scope", function () {
expect(isolateScope.patientDetails).toBeDefined();
});
通过,但我觉得这是在测试错误的东西。
有人可以为我澄清一下吗?
修改
做tasseKATT建议解决了这个问题,但确实打破了其他5个测试。这些测试基本上检查了正在加载的实际模板并确定了它们具有的内容。例如:
it("ul should contain 4 li", function () {
var li = elm.find('li');
expect(li.length).toBe(4);
});
不再有效,因为elm
元素现在是<div upcoming="remembered" patient-details="patient"></div>
html而不是通过模板加载的元素:
<p><a href=""><b>Sign in</b></a> to view your full <br>prescription statuses.</p>
<ul>
<li><span>{{patientDetails.readyForRefill}}</span> Prescriptions Ready for Refill</li>
<li><span>{{patientDetails.readyForRefill}}</span> ReadyFill<sup>®</sup>
<li><span>{{patientDetails.expiringCount}}</span> Expiring Prescriptions</li>
<li><span>{{patientDetails.oneRefillRemaining}}</span> Prescriptions with 1 Refill Left</li>
</ul>
有没有正确加载?虽然值得注意的是,根据谁登录,模板会发生变化,这会导致计算div和p标签的任何尝试与测试无关吗?
由于
答案 0 :(得分:1)
如果要确保指令的范围传递正确的患者详细信息对象,则应在编译元素之前将其放在范围内。然后,您可以通过isolateScope()
检索它并执行验证。
例如:
elm = angular.element('<div upcoming="remembered" patient-details="patient"></div>');
scope = $rootScope.$new();
scope.patient = {
name: 'Lorem Ipsum',
readyForRefill: 1,
progressCount: 2,
upcomingCount: 3,
taggedCount: 4,
expiringCount: 5,
oneRefillRemaining: 9000
};
$compile(elm)(scope);
isolateScope = elm.isolateScope();
和
it("should work", function() {
expect(isolateScope.patientDetails).toBeDefined();
expect(isolateScope.patientDetails.name).toBe('Lorem Ipsum');
});
<强>更新强>
如果您确实需要测试生成的标记,则应使用已编译的元素:
compiled = $compile(elm)(scope);
...
it("ul should contain 4 li", function () {
var li = compiled.find('li');
expect(li.length).toBe(4);
});