我有一个函数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>
);
}
}
My test:
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()
});
我正在尝试测试使用正确的参数调用scrollBy,但是在运行此测试时出现以下错误:
Error: Uncaught [TypeError: document.getElementById(...).getBoundingClientRect is not a function]
抱歉,如果之前已经回答过这个问题,但我看不到任何可以回答我的情况的内容。先感谢您。
scrollBy
在第一个结果上调用getElementById
, and 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!
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)