Arina
Arina

Reputation: 11

Jasmine jQuery loop unit test

How to write a Jasmine unit test for a jQuery for loop? For example if this has to be tested:

$(".class").each(function(index))
{ 
  testFunction()
}

the HTML structure is a list of divs with each div having class as a class.

Upvotes: 1

Views: 593

Answers (1)

Roope Hakulinen
Roope Hakulinen

Reputation: 7405

You need to utilize Jasmine spies to track the calls to function as follows

function testFunction() {
  alert("asd");
}

function foo() {
  $(".class").each(
    function(index) {
      testFunction()
    }
  )
}

describe("foo()", function () {
  var wrapper;
  beforeEach(function() {
    spyOn(window, 'testFunction');
  });

  it("calls testFunction for each element", function () {
    foo(); 
    expect(window.testFunction.calls.count()).toEqual(jQuery(".class").length);
  })
});

I wrote a JSFiddle for you that you can play with.

The main point is the spyOn call that stubs the window object's testFunction. That makes it possible to override every call on the testFunction and react on it any way we wish. On this case we simply let it be executed and take the call count after it with calls.count() and compare it to the amount of elements with class class.

Upvotes: 1

Related Questions