Reputation: 40357
We have a directive that has an optional attribute on it. If the attribute is not there, it provides a default value. The attribute is usually set from data in the scope (i.e., the value of the attribute is usually an expression and not a literal string. See http://jsfiddle.net/8PGZ4/
As such, we are using attrs.$observe
in the directive to set up the scope properly. This works great in the app itself. However, when trying to test this (using Jasmine), the function in the $observe
never gets run. Our test looks something like this:
describe("myDirective", function(){
function getDirectiveScope(compile, rootScope, directiveHTML)
{
return (compile(directiveHTML)(rootScope)).scope();
}
describe("foo", function () {
it("should return the default value", inject(function ($compile, $rootScope) {
var directiveScope = getDirectiveScope($compile, $rootScope, '<div my-directive></div>');
expect(directiveScope.bar).toBe("No Value");
}));
it("should now return the value given", inject(function ($compile, $rootScope) {
$rootScope.foo = "asdf";
var directiveScope = getDirectiveScope($compile, $rootScope, '<div my-directive foo="{{foo}}"></div>');
expect(directiveScope.bar).toBe("asdf");
}));
});
});
These then fail with the following errors:
Expected undefined to be 'No Value'.
Expected undefined to be 'asdf'.
I put a console.log in the $observe
function to try to see what was going on, and when the tests run, I never see the log. Is there an explicit call I have to make for the $observe
to run? Is there something else going on here?
Upvotes: 2
Views: 1071
Reputation: 117370
You need to trigger a digest cycle to let the AngularJS magic happen in your test. Try:
it("should return the default value", inject(function ($compile, $rootScope) {
var directiveScope = getDirectiveScope($compile, $rootScope, '<div my-directive></div>');
$rootScope.$digest();
expect(directiveScope.bar).toBe("No Value");
}));
Upvotes: 2