user1995781 user1995781 - 3 months ago 24
AngularJS Question

How to reset unit test?

I have an unit test that look like this:

describe('myDirective:', function () {

var rootScope, compile;

beforeEach(module('myApp'));

beforeEach(function () {
//inject dependencies
inject(function ($compile, $rootScope) {
rootScope = $rootScope;
compile = $compile;
});
});

it('first test', function () {
var scope = rootScope.$new();
var element = angular.element('<my-directive><div id="myid" style="height:300px"></div></my-directive>');
element.appendTo(document.body);
element = compile(element)(scope);
console.log("#myid height: "+$("#myid").height());
expect($("#myid").height()).toBe(300);
});

it('second test', function () {
var scope = rootScope.$new();
var element = angular.element('<my-directive><div id="myid" style="height:400px"></div></my-directive>');
element.appendTo(document.body);
element = compile(element)(scope);
console.log("#myid height: "+$("#myid").height());
expect($("#myid").height()).toBe(400);
});
});


http://jsfiddle.net/bLg4veso/

It pass the
first test
, but fail on
second test
. The
second test
will always return the height as being set in the
first test
. How can I reset it?

Answer

Since you are appending the element to the body, you need to manually remove it too.

Add this line to end of each test

element.remove();

and it should work.

Comments