如何使用 jest/enzyme 中的“current”属性测试 useRef

2024-03-22

我希望有人能指出我正确的测试方向useRef在下面的组件中。

我有一个类似于下面的组件结构。我正在尝试测试其中的功能otherFunction()但我不确定如何模拟组件引用中的当前属性。以前有人做过这样的事情吗?

const Component = (props) => {
    const thisComponent = useRef(null);
    const otherFunction = ({ current, previousSibling  }) => {
        if (previousSibling) return previousSibling.focus();
        if (!previousSibling && current) return current.focus();
    } 
    const handleFocus = () => {
        const {current} = thisComponent;
        otherFunction(current);
    }
     return (
        <div ref={thisComponent} onFocus={handleFocus}>Stuff In here</div>
    );
};

这是我针对您的案例的测试策略。我用jest.spyOn监视方法React.useRef钩。它可以让我们模拟 SFC 的 ref 对象的不同返回值。

index.tsx:

import React, { RefObject } from 'react';
import { useRef } from 'react';

export const Component = props => {
  const thisComponent: RefObject<HTMLDivElement> = useRef(null);
  const otherFunction = ({ current, previousSibling }) => {
    if (previousSibling) return previousSibling.focus();
    if (!previousSibling && current) return current.focus();
  };
  const handleFocus = () => {
    const { current } = thisComponent;
    const previousSibling = current ? current.previousSibling : null;
    otherFunction({ current, previousSibling });
  };
  return (
    <div ref={thisComponent} onFocus={handleFocus}>
      Stuff In here
    </div>
  );
};

index.spec.tsx:

import React from 'react';
import { Component } from './';
import { shallow } from 'enzyme';

describe('Component', () => {
  const focus = jest.fn();
  beforeEach(() => {
    jest.restoreAllMocks();
    jest.resetAllMocks();
  });
  test('should render correctly', () => {
    const wrapper = shallow(<Component></Component>);
    const div = wrapper.find('div');
    expect(div.text()).toBe('Stuff In here');
  });
  test('should handle click event correctly when previousSibling does not exist', () => {
    const useRefSpy = jest.spyOn(React, 'useRef').mockReturnValueOnce({ current: { focus } });
    const wrapper = shallow(<Component></Component>);
    wrapper.find('div').simulate('focus');
    expect(useRefSpy).toBeCalledTimes(1);
    expect(focus).toBeCalledTimes(1);
  });

  test('should render and handle click event correctly when previousSibling exists', () => {
    const useRefSpy = jest.spyOn(React, 'useRef').mockReturnValueOnce({ current: { previousSibling: { focus } } });
    const wrapper = shallow(<Component></Component>);
    wrapper.find('div').simulate('focus');
    expect(useRefSpy).toBeCalledTimes(1);
    expect(focus).toBeCalledTimes(1);
  });

  test('should render and handle click event correctly when current does not exist', () => {
    const useRefSpy = jest.spyOn(React, 'useRef').mockReturnValueOnce({ current: null });
    const wrapper = shallow(<Component></Component>);
    wrapper.find('div').simulate('focus');
    expect(useRefSpy).toBeCalledTimes(1);
    expect(focus).not.toBeCalled();
  });
});

100%覆盖率的单元测试结果:

 PASS  src/stackoverflow/56739670/index.spec.tsx (6.528s)
  Component
    ✓ should render correctly (10ms)
    ✓ should handle click event correctly when previousSibling does not exist (3ms)
    ✓ should render and handle click event correctly when previousSibling exists (1ms)
    ✓ should render and handle click event correctly when current does not exist (2ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |      100 |      100 |                   |
 index.tsx |      100 |      100 |      100 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       4 passed, 4 total
Snapshots:   0 total
Time:        7.689s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56739670 https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56739670

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 jest/enzyme 中的“current”属性测试 useRef 的相关文章

随机推荐

  • 如何使用 VS2019 解决此 MSB6006 csc.exe 错误 (-2146232797)?

    我刚刚将 VS2019 社区版更新到版本 16 7 2 我的项目开始无法构建 可能是链接步骤 并出现此错误 之前构建得很好 我认为是在 v16 6 something 上 gt Severity Code Description Proje
  • 为jqgrid的每一列添加过滤器

    我有一个jqgrid显示员工的详细信息 我想在每一列中添加一个过滤器 用户可以使用该过滤器输入公司名称 网格显示与网格中的过滤器匹配的所有员工行 谷歌搜索了很多但没有成功 任何参考示例 链接都会有帮助 当您在文本框中键入测试用例的名称时 您
  • 单元格pyqt中的小部件对齐

    我正在 PyQT4 和 Python 2 7 中开发一些工具 但遇到了一个小问题 我有 3 个按钮存储在小部件中 该小部件位于表格 QTableWidget 的单元格中 所以我的问题是我无法将小部件与单元格顶部对齐 并且工具无法将行高调整为
  • 如何遵循 powershell 中的快捷方式

    在 powershell 中 您使用cd dir进入目录dir But if dir是目录的快捷方式 cd dir and cd dir lnk两者都会给出错误 说该目录不存在 那么我该如何遵循这条捷径呢 在Linux中cd dir 正常工
  • 如何爆掉 yeoman index.html 缓存

    当我部署 Angular 应用程序的新版本时 旧版本仍然存在 只是 修复的解决方法是对浏览器进行 硬 刷新 这不是一个可接受的解决方案 我在我的项目中使用 Yeoman 生成器角度 我看了看Gruntfile js并看到它执行了一个在构建期
  • 如何通过 stackexchange api 调用检索 stackoverflow 标签使用计数?

    我想通过 StackExchange API 检索 Ruby 或 Java 等语言的 标签使用计数 基本上我想通过 API 调用检索这些数字 https stackoverflow com tags https stackoverflow
  • 检测是否只给出整数的程序是否进入无限循环

    program to detect whether only integer has been given or not int main int a b s printf Enter two proper number n BEGIN s
  • 如何在 Azure 虚拟机中伪造 OpenGL?

    我想在我的 Azure VM Windows Server 2008 中运行一些需要 OpenGL 2 0 的程序 然而 虚拟机没有视频硬件 我如何才能让程序相信我有足够好的视频卡 如果我没有虚拟显卡 我该如何在云中进行所有开发呢 您可以放
  • Mongo / Mongoose 聚合 - $redact 和 $cond 问题

    我很幸运能够得到另一个SO问题的精彩答案Mongo Mongoose 按日期聚合 https stackoverflow com questions 43864813 mongo mongoose aggregating by date来自
  • 静态多态性定义和实现[关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我对这个概念有一些疑问静态多态性我有时听说 您可能主要在 C 上下文中解释它们 但我希望在适用的情况下提供与语言无关的答案 因此标记
  • 新的空 iOS 应用程序存在数十处内存泄漏

    在一款新的 从头开始的单视图 iOS 应用程序上使用 Leaks Instruments 工具报告了 23 起泄漏 这似乎不对 我错过了什么吗 重复运行会产生不同的泄漏计数 从 16 到 35 重现步骤遵循此屏幕截图 类似的未回答的问题发布
  • 绘制一个矩形 google.maps.Polygon 给定其中心点和尺寸

    我正在编写一个 PHP 脚本 它接受 XML 输入 解析它 然后显示 最终旋转 矩形和椭圆区域 因为区域可以旋转 所以我必须使用google maps Polygon并不是Rectangle 为了处理旋转我希望使用谷歌地图多边形旋转 htt
  • 如何以编程方式从 spring-boot-actuator 获取指标?

    我们在生产中有一个弹簧应用程序 它不是 Spring boot 我发现这个帖子 https stackoverflow com questions 26913087 use spring boot actuator without a sp
  • 我可以在 Node 中执行字符串命令吗?

    如果我构造一个存储在字符串变量中的函数或命令列表 有没有办法可以在节点中执行它们并保留另一个变量中返回的内容 IE var result executeMyCoolStringCommands myStringVariableWithCom
  • Phonegap数据库问题-在数据库中存储图像

    我正在尝试使用以下选项制作一个非常基本的库存应用程序 添加库存中物品的照片 我已拥有一切 除了照片部分外正在工作 我看过这个 http phonegap pbworks com iPhone 3A Camera API http phone
  • 如何让Gedit看起来像Textmate?

    我想让 Gedit 看起来像 Textmate 并且行为也像它 我在网上阅读了很多教程 但找不到易于遵循的指南 我正在使用 Ubuntu 11 04 并希望将其用于 Ruby on Rails 和其他网络语言 我只想要核心功能 例如类 项目
  • 如何从 Docker 控制 fluidd 日志标签

    当前设置正在运行 Docker 容器fluentd driver docker run log driver fluentd my container 这工作起来很容易 将标准输出发送到主机上本地运行的 Fluentd 系统 我想控制流利t
  • MapStruct - @Mapper 注释不创建 bean

    我从此来源下载了应用程序https github com springframeworkguru spring5 mvc rest tree vendor api https github com springframeworkguru s
  • Bootstrap 5 有内置水平线吗?

    我正在寻找样式或彩色水平线 最好有成功 主要 警告类别 类似的概念彩色链接 https getbootstrap com docs 5 0 helpers colored links 我在 Bootstrap 的网站上找不到这个主题 我找到
  • 如何使用 jest/enzyme 中的“current”属性测试 useRef

    我希望有人能指出我正确的测试方向useRef在下面的组件中 我有一个类似于下面的组件结构 我正在尝试测试其中的功能otherFunction 但我不确定如何模拟组件引用中的当前属性 以前有人做过这样的事情吗 const Component