【发布时间】:2020-09-02 08:57:22
【问题描述】:
给定以下组件:
import * as React from "react";
import "./styles.css";
export default function App() {
const scrollContainerRef = React.useRef<HTMLDivElement | null>(null);
const handleClick = () => {
scrollContainerRef?.current?.scrollBy({ top: 0, left: 100 });
};
return (
<div aria-label="wrapper" ref={scrollContainerRef}>
<button onClick={handleClick}>click</button>
</div>
);
}
如何使用 Jest 和 React 测试库编写测试以检查单击按钮时是否在包装器上触发 scrollBy?
我尝试了以下方法,但它似乎不起作用:
test('Clicking on button should trigger scroll',() => {
const myMock = jest.fn();
Object.defineProperty(HTMLElement.prototype, 'scrollBy', {
configurable: true,
value: myMock(),
})
render(<MyComponent />)
fireEvent.click(screen.getByText(/click/i))
expect(myMock).toHaveBeenCalledWith({top: 0, left: 100})
})
【问题讨论】:
标签: reactjs mocking jestjs react-hooks react-testing-library