简体   繁体   English

无法在Jasmine测试中获取scrollTop值

[英]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. 这是我对Stack Overflow的第一个问题,Jasmine对我来说相当新,所以我希望我在这里做得很好。

I have a Jasmine test where I try to set the scroll position of my page to a certain value. 我有一个Jasmine测试,我尝试将页面的滚动位置设置为某个值。 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. 结果: 预期0到100。

I set the scrollTop to 100 and expect it to be just that on the next line. 我将scrollTop设置为100并期望它就在下一行。 How does this test fail? 该测试如何失败?

If it matters, I'm using Jasmine 1.3.1 with requirejs and jasmine-jquery as an extension. 如果重要的话,我使用带有requirejs的Jasmine 1.3.1和jasmine-jquery作为扩展。

I can't see what setFixtures does, but my guess is because; 我看不出setFixtures作用,但我的猜测是因为;

  • The DOM nodes created have not been appended anywhere in the live DOM. 创建的DOM节点尚未附加到实时DOM中的任何位置。
  • The DIV is not styled to be scrollable. DIV没有被设计为可滚动的样式。
  • The DIV does not have enough content to show a scrollbar. DIV没有足够的内容来显示滚动条。

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. 我希望这有帮助,谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM