在带有酶的React中测试去抖动方法 [英] Testing debounced method in React with Enzyme
问题描述
//Component
import _ from 'lodash';
constructor(props) {
super(props);
this.onScroll = _.debounce(::this.onScroll, 100);
}
onScroll() {
//some code
}
//Test
it('onScroll', () => {
const component = shallow(<Component />);
component.instance().onScroll(); //Dosn't call method
})
我使用酶作为渲染组件,并使用lodash进行去抖动
。如何调用 component.instance()。onScroll()
?
I use enzyme for render component, and lodash for debounce
. How to call component.instance().onScroll()
?
推荐答案
TL; DR;使用 lolex
来提前< a href = https://github.com/facebook/jest/issues/2234#issuecomment-332831046 rel = nofollow noreferrer>在模拟计时器时用于测试 _。debounce
TL;DR; use lolex
to advance in time while mocking timers for testing _.debounce
我准备通过 useFakeTimers
和 advanceTimersByTime
。
一段时间后,我发现它可以与 _。throttle
一起使用,但 _。debounce
。
然后我在Jest的回购中发现了问题已报告。此外,还有专门的错误报告 _.debounce打破了假计时器 ,我没有看不到它已解决(忽略它的状态,并查看那里的最后评论)。
After some time I've found it works with _.throttle
but not _.debounce
.
And then I've found issue reported in Jest's repo. Also there is dedicated bug report "_.debounce breaks fake timers" and I don't see it's resolved(ignore its status and check last comments there).
根据veeeeery 详细说明 _。debounce
不仅要放置 setTimeout
还会检查时差。因此,我们还应该模拟 Date.now
Jest的 jest.runOnlyPendingTimers
或 jest.advanceTimersByTime
不要。
According to veeeeery detailed explanation _.debounce
not just put setTimeout
but also checks time difference. So we should mock also Date.now
that Jest's jest.runOnlyPendingTimers
or jest.advanceTimersByTime
don't do.
因此对于简单的组件,如
So for simple component like
function Debounced({onClick}) {
return <button onClick={_debounce(onClick,500)}>Click Me</button>;
}
下次测试已通过:
let clock = lolex.install();
const onClick = jest.fn();
const wrapper = shallow(<Debounced onClick={onClick} />);
const button = wrapper.find('button').at(0);
button.simulate('click');
button.simulate('click');
button.simulate('click');
clock.tick(510);
expect(onClick).toHaveBeenCalledTimes(1);
clock.uninstall();
PS,确保可以运行 lolex.install()
和 clock.uninstall()
在 beforeEach
/ afterEach $ c $中c>
PS for sure you could run lolex.install()
and clock.uninstall()
in beforeEach
/afterEach
这篇关于在带有酶的React中测试去抖动方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!