在AngularJS中对隔离范围进行单元测试的好方法是什么
指令段
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');