jestjs - 在 Jest 中测试 ScrollIntoView

标签 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();
})

但测试失败并出现类型错误:无法设置未定义的属性“scrollIntoView”

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

最佳答案

你需要添加一个 HTMLElementbottomdocument:

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!
})

关于jestjs - 在 Jest 中测试 ScrollIntoView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55190401/

相关文章:

typescript - 如何更新 React/TypeScript 项目中的快照?

node.js - 如何使用 node-fetch、supertest 和 typescript 设置 fetch-mock

javascript - 类型 'xxx' 上不存在属性 'Readonly<{}>'

angular - 将 Angular Testing fakeAsync 与 jest it.each 一起使用

jestjs - 使用 jest 测试框架的 LWC 测试引发错误 - 元素的未知公共(public)属性 "smalldevicesize"

javascript - Jest 收到 : serializes to the same string

javascript - 如何使用 axios 和 async/await 断言错误

javascript - super 测试未找到错误测试快速端点

javascript - 如何在 ReactJS/Typescript 应用程序中使用 Jest 测试类内的公共(public)异步函数

javascript - 类型错误 : dispatch is not a function when I try to test a method using JEST