What is a good way to unit test an isolated area in AngularJS
JSFiddle showing unit test
Fragment of the directive
scope: {name: '=myGreet'}, link: function (scope, element, attrs) {
I want the directive to listen to changes - this does not work with an isolated area:
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: I got it for work, checking to see if the expected observers were added to the children area, but it is very fragile and probably using accessories in an undocumented way (which can be changed without notice!).
//this is super brittle, is there a better way!? elm = compile(validHTML)(scope); expect(elm.scope().$$watchers[0].exp).toBe('name');
UPDATE 2: As I said, it's fragile! The idea still works, but in newer versions of AngularJS, the accessor has changed from scope() to isolateScope() :
//this is STILL super brittle, is there a better way!? elm = compile(validHTML)(scope); expect(elm.isolateScope().$$watchers[0].exp).toBe('name');
javascript angularjs unit-testing angularjs-directive jasmine
daniellmb Jun 28 '13 at 19:01 2013-06-28 19:01
source share