首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在React中用setIntervale测试UseEffect?

如何在React中用setIntervale测试UseEffect?
EN

Stack Overflow用户
提问于 2020-09-18 20:53:11
回答 2查看 121关注 0票数 1

这是Original Issue

我有一个通知组件,其中autohide是控制通知可见性的属性:

代码语言:javascript
复制
    <Notification {...notification} darkmode autohide >
        <Media src={MEDIA_PATH} link='https://www.github.com' />
    </Notification>

在我的Notification组件中:

代码语言:javascript
复制
const Notification = ({ type, data, style, action, darkmode, autohide, children }) => {
    
    const [visible, setVisible] = useState(true);

    useEffect(() => {
        if (autohide) {
            setInterval(() => setVisible(false), 5000);
        }
        return () => {
            clearInterval();
        }
    }, [autohide]);

 return (visible && <Wrapper {...props}> { children }</Wrapper>);

}

我正在使用酶,我想测试一下useEffect

代码语言:javascript
复制
it("should hide the Notification after 5 seconds", () => {
        const wrapper = shallow(<Notification {...props} autohide />)
        // How to say that the component will be hidden after 5 seconds based on its internal state?
    });

我试过了:

代码语言:javascript
复制
    it('should hide the Notification after 5 seconds', () => {
        expect(wrapper.isEmptyRender()).toBeTruthy();
    });

但它不会产生影响。

EN

回答 2

Stack Overflow用户

发布于 2020-09-18 21:35:35

尝试设置测试的等待时间-

使用props

  • 设置组件验证它的呈现时间在测试中等待5秒

  • Call wrapper.update()

  • Verify
  1. 已到达该时间并停止呈现。
票数 0
EN

Stack Overflow用户

发布于 2020-09-18 21:43:21

Jest有一些fake timers。在你的单元测试中等待5秒不是一个好主意,因为它们应该是快速的。

像这样的东西应该是有效的:

代码语言:javascript
复制
jest.useFakeTimers();

it("should hide the Notification after 5 seconds", () => {
    const wrapper = shallow(<Notification {...props} autohide />);
        
    jest.runAllTimers();

    expect(wrapper.isEmptyRender()).toBeTruthy();
});

这可能不会立即起作用(我不确定异步是如何处理的),但引用的页面应该会给你一些想法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63956170

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档