在Jest中测试ScrollIntoView

时间:2019-03-15 20:42:13

标签: jestjs

具有使用scrollIntoView的功能

export const scrollDown = () => {
    document.querySelector('.bottom').scrollIntoView({ 
        behavior: 'smooth' 
    });
}

我在这里进行了这样的测试

describe('scrollDown', () => {
    let scrollIntoViewMock = jest.fn();
    window.HTMLElement.prototype.scrollIntoView = scrollIntoViewMock;
    scrollDown()
    expect(scrollIntoViewMock).toBeCalled();
})

但是测试失败并出现TypeError:无法将属性'scrollIntoView'设置为未定义

该测试来自于另一个针对scrollIntoView测试问题的答案。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您需要将HTMLElement类的bottom添加到document

const scrollDown = () => {
  document.querySelector('.bottom').scrollIntoView({ 
      behavior: 'smooth' 
  });
}

test('scrollDown', () => {
  document.body.innerHTML = '<div class="bottom"></div>';
  const scrollIntoViewMock = jest.fn();
  HTMLElement.prototype.scrollIntoView = scrollIntoViewMock;
  scrollDown();
  expect(scrollIntoViewMock).toBeCalledWith({ behavior: 'smooth' });  // Success!
})