【发布时间】:2013-06-26 15:32:51
【问题描述】:
在 AngularJS 中对隔离范围进行单元测试的好方法是什么
指令sn-p
scope: {name: '=myGreet'},
link: function (scope, element, attrs) {
//show the initial state
greet(element, scope[attrs.myGreet]);
//listen for changes in the model
scope.$watch(attrs.myGreet, function (name) {
greet(element, name);
});
}
我想确保指令正在侦听更改 - 这不适用于隔离范围:
it('should watch for changes in the model', function () {
var elm;
//arrange
spyOn(scope, '$watch');
//act
elm = compile(validHTML)(scope);
//assert
expect(scope.$watch.callCount).toBe(1);
expect(scope.$watch).toHaveBeenCalledWith('name', jasmine.any(Function));
});
更新: 我通过检查是否将预期的观察者添加到子作用域来使其工作,但它非常脆弱,并且可能以未记录的方式使用访问器(也可能会更改,恕不另行通知!)。
//this is super brittle, is there a better way!?
elm = compile(validHTML)(scope);
expect(elm.scope().$$watchers[0].exp).toBe('name');
更新 2:
正如我所提到的,这很脆弱!这个想法仍然有效,但在较新版本的 AngularJS 中,访问器已从 scope() 更改为 isolateScope():
//this is STILL super brittle, is there a better way!?
elm = compile(validHTML)(scope);
expect(elm.isolateScope().$$watchers[0].exp).toBe('name');
【问题讨论】:
-
你找到设置间谍的方法了吗?
-
@Tushar 不是真的,因为以前有办法让它工作,但它可能会在没有通知的情况下更改,因此使用风险自负。
标签: javascript unit-testing angularjs jasmine angularjs-directive