單元測試隔離範圍指令什麼是在AngularJS單元測試隔離範圍的好辦法片斷</p> <p><a href="http://jsfiddle.net/daniellmb/b7BRR">JSFiddle showing unit test</a></p> <p>指令如何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));
});
UPDATE: 我得到了它的如果預期觀察家被添加到子範圍檢查工作,但它是非常脆,很可能使用無證方式的訪問者(又名隨時更改,恕不另行通知!)。
//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
@Tushar並不像以前那樣有辦法讓它起作用,但它可能會在沒有通知的情況下發生變化,所以請自擔風險。 – daniellmb