JSFiddle - React, Tailwind, and code Playground
by Daniel Lamb
HTML
<script src="http://daniellmb.github.com/jasmine-run/jasmine-1.3.1-run.js"></script>
<script src="http://code.angularjs.org/1.1.1/angular-mocks.js"></script>
<!-- EXAMPLE HTML
<div ng-app="myApp">
<div ng-controller="myCtrl">
<input type="text" ng-model="name" placeholder="name" />
<b my-greet="name"></b>
</div>
</div>
-->
JavaScript
//AngularJS Directive with Isolated Scope
angular.module('myApp', [])
.controller('myCtrl', function ($scope) {
$scope.name = 'World';
})
.directive('myGreet', function () {
function greet(elm, name) {
elm.text('Hello ' + name);
}
return {
//if you comment out the line below the tests pass
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);
});
}
};
});
//*
//Directive Unit Tests
describe('myGreet directive:', function () {
var scope, compile, validHTML;
validHTML = '<span my-greet="name"></span>';
beforeEach(module('myApp'));
beforeEach(function(){
//inject dependencies
inject(function ($compile, $rootScope) {
scope = $rootScope.$new();
compile = $compile;
});
});
describe('when created', function () {
it('should greet the name provided', function () {
var elm;
//arrange
scope.name = 'Test';
//act
elm = compile(validHTML)(scope);
//assert
expect(elm.text()).toBe('Hello Test');
});
it('should watch for changes in the model', function () {
var elm;
//this is super brittle is there a better way!?
elm = compile(validHTML)(scope);
expect(elm.scope().$$watchers[0].exp).toBe('name');
/* This version works fine when the scope is NOT isolated
spyOn(scope, '$watch');
elm = compile(validHTML)(scope);
expect(scope.$watch.callCount).toBe(1);
expect(scope.$watch).toHaveBeenCalledWith('name',...