Moh*_*med 3 javascript mocking spy reactjs jestjs
我有一个函数 handleClick,它在元素上使用 scrollBy,该元素使用 getBoundingClientRect 获取其第一个参数。我正在尝试使用玩笑/酶来测试这个。
class myClass extends Component {
...
...
handleClick () {
document.getElementById('first-id').scrollBy(document.getElementById('second-id').getBoundingClientRect().width, 0);
}
render() {
return (
<button className="my-button" onClick={this.handleClick()}>scroll</button>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我的测试:
it('calls scrollBy with correct params', () => {
const props = {};
myClassWrapper = mount(<myClass {...props} />);
const scrollBySpy = jest.fn();
global.document.getElementById = jest.fn(() => ({ scrollBy: scrollBySpy }));
myClassWrapper.find('my-button').simulate('click');
// expect(scrollBySpy).toHaveBeenCalledWith()
});
Run Code Online (Sandbox Code Playgroud)
我正在尝试测试是否使用正确的参数调用了 scrollBy,但是在运行此测试时出现以下错误:
Error: Uncaught [TypeError: document.getElementById(...).getBoundingClientRect is not a function]
Run Code Online (Sandbox Code Playgroud)
抱歉,如果之前已经回答过这个问题,但我看不到任何可以回答我的情况的内容。先感谢您。
scrollBy被称为上的第一个结果getElementById,而getBoundingClientRect被称为上的第二个结果getElementById,所以你需要包括的对象,你在模拟正在返回两种功能。
这是一个可以帮助您入门的工作示例:
import * as React from 'react';
import { mount } from 'enzyme';
class MyClass extends React.Component {
handleClick() {
document.getElementById('first-id').scrollBy(document.getElementById('second-id').getBoundingClientRect().width, 0);
}
render() {
return (
<button className="my-button" onClick={this.handleClick}>scroll</button>
);
}
}
it('calls scrollBy with correct params', () => {
const props = {};
const myClassWrapper = mount(<MyClass {...props} />);
const scrollBySpy = jest.fn();
const getBoundingClientRectSpy = jest.fn(() => ({ width: 100 }));
global.document.getElementById = jest.fn(() => ({
scrollBy: scrollBySpy,
getBoundingClientRect: getBoundingClientRectSpy // <= add getBoundingClientRect
}));
myClassWrapper.find('.my-button').simulate('click');
expect(scrollBySpy).toHaveBeenCalledWith(100, 0); // Success!
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6233 次 |
| 最近记录: |