Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failing to get the scrollTop value inside a Jasmine test

This is my first question to Stack Overflow and Jasmine is fairly new to me, so I hope I'm doing ok here.

I have a Jasmine test where I try to set the scroll position of my page to a certain value. The actual code is pretty complex, but I managed to make a more simple example of the failing test:

it("should set scrollTop to equal 100", function () {
  setFixtures("<div id='page' style='height: 1000px;'>Page content</div>");

  spyOn($.fn, "scrollTop");
  $("#page").scrollTop(100);

  expect($.fn.scrollTop).toHaveBeenCalledWith(100); // this test passes
  expect($("#page").scrollTop()).toEqual(100);
});

The result: Expected 0 to equal 100.

I set the scrollTop to 100 and expect it to be just that on the next line. How does this test fail?

If it matters, I'm using Jasmine 1.3.1 with requirejs and jasmine-jquery as an extension.

like image 547
balzafin Avatar asked Nov 07 '14 18:11

balzafin


People also ask

Why is scrollTop always 0?

An element's scrollTop is a form of distance measurement regarding an element's top to its topmost visible content. When an element content does not generate a vertical scrollbar, then its scrollTop value defaults to 0." Since the content of inner doesn't generate a scrollbar, scrollTop is 0 .

Can scrollTop be negative?

scrollTop doesn't respond to negative values; instead, it sets itself back to 0 . If set to a value greater than the maximum available for the element, scrollTop settles itself to the maximum value.


1 Answers

I can't see what setFixtures does, but my guess is because;

  • The DOM nodes created have not been appended anywhere in the live DOM.
  • The DIV is not styled to be scrollable.
  • The DIV does not have enough content to show a scrollbar.

Here is a plain example;

var div = document.createElement('div');
div.style.height = '100px';
div.style.width = '100px';

// ensure the content has a track for scrollbars (won't work without this)
div.style.overflow = 'scroll';

// it also needs enough content to actually be scrollable (won't work without this)
div.innerHTML = '<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x';

// needs to be appended to the live DOM (won't work without this)
document.body.appendChild(div);

// we can now set this value
div.scrollTop = 50;

// and read it back
console.log(div.scrollTop);
// == 50

I hope this helps, thanks.

like image 55
Jamie Mason Avatar answered Sep 28 '22 04:09

Jamie Mason