AngularJS directive是自定义的HTML扩展,它必须与DOM元素绑定,那我们是不是就不能对directive代码做单元测试了呢?AngularJS的系统架构优势使得对directive做单元测试成为可能。其秘密就在$compile编译服务,$compile可以把模版和scope结合生成element。在单元测试里,通过$rootScope 和带有directive 的模版生成element,我们便可以断言生成的element是否满足我们的期望,并且可以通过改变$rootScope的model值, 来断言element的各个属性是否也如我们期望一样变化。下面的例子,是AngularJS自己对
ng-disabled
的单元测试代码:
element
=
$compile
(
'
'
)(
$rootScope
) //创建
$rootScope
.
isDisabled
=
false
; //设置model值
$rootScope
.
$digest
(); //使之生效
expect
(
element
.
attr
(
'disabled'
)).
toBeFalsy
(); // 断言
$rootScope
.
isDisabled
=
true
;//改变model值
$rootScope
.
$digest
();
//使之生效
expect
(
element
.
attr
(
'disabled'
)).
toBeTruthy
();
// 断言
}));
是不是很简单?
it
(
'should bind disabled'
,
inject
(
function
(
$rootScope
,
$compile
)
{
是不是很简单?