StackOverflow_24246811: testing-ng-if-using-compile
Illustration of answer to http://stackoverflow.com/questions/24246811/testing-ng-if-using-compile.
by ExpertSystem
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine-html.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/boot.js"></script>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine.css">
<script src="http://code.angularjs.org/1.2.18/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.18/angular-mocks.js"></script>
JavaScript
/* App-specific code */
var app = angular.module('myApp', []);
/* Test-specific code */
angular.module('specApp', ['myApp']);
describe('In my Angular app', function () {
describe('ngIf', function () {
var $compile;
var scope;
var template;
beforeEach(function () {
module('specApp');
inject(function (_$compile_, $rootScope) {
$compile = _$compile_;
scope = $rootScope.$new();
template = '<div><h1 ng-if="test">Hello, world !</h1></div>';
//template = '<div ng-if="test"><h1>Hello, world !</h1></div>';
// Uncomment the above line to make the tests fail
});
});
it('should add the node if the condition is truthy', function () {
scope.test = true;
var elem = $compile(template)(scope);
scope.$digest();
expect(elem.text()).toContain('Hello, world !');
});
it('should remove the node if the condition is falsy', function () {
scope.test = false;
var elem = $compile(template)(scope);
scope.$digest();
expect(elem.text()).not.toContain('Hello, world !');
});
});
});