使用 Jest 和 Enzyme 测试 FaC 时未找到 React Node 节点

2024-02-03

我正在 React Native 中构建一个应用程序。我们最近开始在应用程序中使用 TypeScript,我的任务是迁移单元测试。有一项测试奇迹般地失败了。

该应用程序有一个<LoginForm />使用Formik https://github.com/jaredpalmer/formik.

//... imports

export interface FormValues {
  email: string;
  password: string;
}

export interface Props {
  navigation: NavigationScreenProp<any, any>;
}

export default class LoginForm extends Component<Props, object> {
  handleSubmit = (values: FormValues, formikBag: FormikActions<FormValues>) => {
    // ... api calls and stuff
  };

  renderForm = ({
    values,
    handleSubmit,
    setFieldValue,
    touched,
    errors,
    setFieldTouched,
    isValid,
    isSubmitting
  }: FormikProps<FormValues>) => (
    <View style={styles.container}>
      // ... two inputs and a button
    </View>
  );

  render() {
    return (
      <Formik
        initialValues={{ email: "", password: "" }}
        onSubmit={(values: FormValues, formikBag: FormikActions<FormValues>) =>
          this.handleSubmit(values, formikBag)
        }
        validationSchema={<some_schema>}
        render={(formikBag: FormikProps<FormValues>) => this.renderForm(formikBag)}
      />
    );
  }
}

这就是单元测试寻找子函数的方式renderForm():

describe("renderForm", () => {
  let formWrapper: ShallowWrapper;
  beforeEach(() => {
    let formikBagMock: any = {
      values: { email: "Test Email", password: "testpassword" },
      handleSubmit: jest.fn(),
      setFieldValue: jest.fn(),
      errors: { email: "Test error", password: "" },
      touched: { email: true, password: false },
      setFieldTouched: jest.fn(),
      isValid: false,
      isSubmitting: false
    };
    formWrapper = shallow(wrapper.instance().renderForm(formikBagMock));
  });

  it("should render a <View />", () => {
    expect(formWrapper.find("View")).toHaveLength(1);
  });

  it("should render two <Input />", () => {
    expect(formWrapper.find("Input")).toHaveLength(2);
  });

  it("should render a <Button />", () => {
    expect(formWrapper.find("Button")).toHaveLength(1);
  });

  describe("styling", () => {
    it("should give the <View /> the 'container' style", () => {
      expect(formWrapper.find(View).prop("style")).toEqual(styles.container);
    });
  });
});

问题是,当这个测试通过时.js它失败了.tsx.

The error thrown looks like this:

 ● LoginForm › rendering › renderForm › should render a <Button />

    expect(received).toHaveLength(length)

    Expected value to have length:
      1
    Received:
      {Symbol(enzyme.__root__): {Symbol(enzyme.__root__): [Circular], Symbol(enzyme.__unrendered__): <Component style={{"alignItems": "center", "flex": 1, "justifyContent": "space-evenly"}}><Input autoCapitalize="none" editable={true} errorMessage="Test error" keyboardType="email-address" onBlur={[Function onBlur]} onChangeText={[Function onChangeText]} placeholder="Email address" value="Test Email" /><Input autoCapitalize="none" editable={true} onBlur={[Function onBlur]} onChangeText={[Function onChangeText]} placeholder="Password" secureTextEntry={true} value="testpassword" /><Button TouchableComponent={[Function anonymous]} buttonStyle={{"backgroundColor": "#DC4F19"}} clear={false} containerStyle={{"paddingVertical": 5, "width": "33%"}} disabled={true} disabledStyle={{"backgroundColor": "#DC4F19", "opacity": 0.3}} disabledTitleStyle={{"color": "white"}} iconRight={false} loading={false} loadingProps={{"color": "white", "size": "large"}} onPress={[Function mockConstructor]} raised={false} title="Log In" titleStyle={{"color": "white"}} /></Component>, Symbol(enzyme.__renderer__): {"batchedUpdates": [Function batchedUpdates], "getNode": [Function getNode], "render": [Function render], "simulateError": [Function simulateError], "simulateEvent": [Function simulateEvent], "unmount": [Function unmount]}, Symbol(enzyme.__node__): {"instance": null, "key": undefined, "nodeType": "function", "props": {"children": [Function anonymous]}, "ref": null, "rendered": [Function anonymous], "type": {"$$typeof": Symbol(react.context), "Consumer": [Circular], "Provider": {"$$typeof": Symbol(react.provider), "_context": [Circular]}, "_calculateChangedBits": null, "_currentRenderer": null, "_currentRenderer2": null, "_currentValue": false, "_currentValue2": false, "unstable_read": [Function bound readContext]}}, Symbol(enzyme.__nodes__): [{"instance": null, "key": undefined, "nodeType": "function", "props": {"children": [Function anonymous]}, "ref": null, "rendered": [Function anonymous], "type": {"$$typeof": Symbol(react.context), "Consumer": [Circular], "Provider": {"$$typeof": Symbol(react.provider), "_context": [Circular]}, "_calculateChangedBits": null, "_currentRenderer": null, "_currentRenderer2": null, "_currentValue": false, "_currentValue2": false, "unstable_read": [Function bound readContext]}}], Symbol(enzyme.__options__): {"adapter": {"options": {"enableComponentDidUpdateOnSetState": true, "lifecycles": {"componentDidUpdate": {"onSetState": true}, "getDerivedStateFromProps": true, "getSnapshotBeforeUpdate": true, "setState": {"skipsComponentDidUpdateOnNullish": true}}}}, "attachTo": undefined, "hydrateIn": undefined}}, Symbol(enzyme.__unrendered__): null, Symbol(enzyme.__renderer__): {"batchedUpdates": [Function batchedUpdates], "getNode": [Function getNode], "render": [Function render], "simulateError": [Function simulateError], "simulateEvent": [Function simulateEvent], "unmount": [Function unmount]}, Symbol(enzyme.__node__): undefined, Symbol(enzyme.__nodes__): [], Symbol(enzyme.__options__): {"adapter": {"options": {"enableComponentDidUpdateOnSetState": true, "lifecycles": {"componentDidUpdate": {"onSetState": true}, "getDerivedStateFromProps": true, "getSnapshotBeforeUpdate": true, "setState": {"skipsComponentDidUpdateOnNullish": true}}}}, "attachTo": undefined, "hydrateIn": undefined}}
    received.length:
      0

      61 |
      62 |       it("should render a <Button />", () => {
    > 63 |         expect(formWrapper.find("Button")).toHaveLength(1);
         |                                            ^
      64 |       });
      65 |
      66 |       describe("styling", () => {

Enzyme怎么突然找不到节点了?我什至尝试导入组件View, Button and Input直接并将其传递给find()而不是字符串,但它不会改变任何东西。我究竟做错了什么?


你可以比较一下formWrapper.debug() in the .js and .tsx文件看看有什么不同。

既然你正在使用Shallow Rendering https://enzymejs.github.io/enzyme/docs/api/shallow.html你可能需要dive() https://enzymejs.github.io/enzyme/docs/api/ShallowWrapper/dive.html to hit Button. Use console.log(formWrapper.debug())看看渲染了什么。

If only View已渲染,请尝试:expect(formWrapper.dive().find("Button")).toHaveLength(1)

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

使用 Jest 和 Enzyme 测试 FaC 时未找到 React Node 节点 的相关文章

随机推荐

  • 如何合并 2 个 javascript 对象,如果另一个对象中不存在属性,则填充一个对象中的属性?

    如果我有一个 javascript 对象 assoc 数组定义如下 function somefunction options var defaults prop1 foo prop2 bar Do stuff here 我想使用它作为该函
  • 如何使用pickle保存sklearn模型

    我想使用 Pickle 转储并加载我的 Sklearn 训练模型 怎么做 Save import pickle with open model pkl wb as f pickle dump model f Load with open m
  • NSTableView 左上角的奇怪矩形(NSBannerView)

    我正在开发 macOS 应用程序 但遇到了一个奇怪的问题 在我的 NSTableView 的左上角 标题上方 显示一个灰色矩形 我在 NSTableView 后面添加了一个 NSBox 以便在屏幕截图中更清晰 通过调试视图层次结构 我看到它
  • 页面重新加载后显示附加图像

    我正在将图像附加到页面中 还有一个复选框可以查看附加项目和隐藏附加项目 我将数据保存在 JSON 数组中 即使在重新加载选项卡后 我也想显示这些附加图像 当您通过 JavaScript 对 DOM 进行动态更改时 它们不是持久的 如果你想做
  • 使 Azure DocumentDB 不返回服务字段

    我在节点应用程序中为 Azure DocumentDB 使用类似 SQL 的语法 这是方法代码 client queryDocuments collection self SELECT FROM root toArray function
  • 在数据库中存储不同图像的最佳方式是什么?

    为不同目的存储图像的最佳方法 关于数据库设计 是什么 我有一堆用户照片 还有另外 5 组不同的照片 类似于用户照片 但与用户照片没有联系 最好是将所有照片存储在一个数据库表中并尝试从该表中引用它们 还是最好为每组照片创建不同的表 我可以看到
  • masm 错误 A2075:跳转目的地太远:30 个字节

    我的女士给我布置了一个作业 其中我必须编写一个程序 该程序将通过键盘获取输入并检查嵌套括号的常规顺序 例如 input output 正确的格式 input output 不正确 我的程序 model small stack 100h 38
  • Spring AutoPopulateList 最大大小?

    我对 Spring 自动填充列表有疑问 我的用例如下 管理可以访问应用程序的用户列表 在 GUI 方面 我使用自动完成字段来搜索用户并将用户添加到右侧的表中 用户也可以从表中删除 当 GUI 用户提交时 GUI 会动态构建一个包含用户字段的
  • 读取文本文件的行并收到 Charmap 解码错误

    我使用 python3 3 和 sqlite3 数据库 我有一个大约 270mb 的大文本文件 我可以在 Windows7 中使用写字板打开它 该文件中的每一行如下所示 术语 t编号 n 我想读取每一行并将值保存在数据库中 我的代码如下所示
  • java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

    我有一个旧的 struts 1 应用程序 一直使用 Ant 构建 我正在将其转换为使用 Maven 我的应用程序的结构是模块化的 在包含模块中进行依赖管理 包含模块的 dep mgmt 部分包含
  • 在 switch-case 中创建一个对象

    我使用 Visual Studio 2008 C 在我的开关案例中 a 想要创建一个对象 但我不工作 我无法在开关盒中创建对象 对吗 如果这是正确的 解决这个问题的最佳方法是什么 创建该对象的新方法 编辑代码 switch causwahl
  • Laravel 在身份验证后重定向到登录

    PROBLEM 我正忙于我的第一个 Laravel 应用程序 尽管我看到了这种编写方式的好处 但我很难理解其中的一些行为 当我尝试登录时 我被重定向到登录页面 看起来用户身份验证正确 但无论如何它都会重定向到登录页面 我拥有的 我的用户表如
  • 在 python 中迭代和更新列表[重复]

    这个问题在这里已经有答案了 我无法理解为什么下面的代码会无限期地出现 循环 当我不使用复制列表时 list Mohit kumar sffsfshfsd for w in list if len w gt 5 list insert 0 w
  • 在 JPA 上选择 DISTINCT

    我有一张桌子ISO 4217 值 https en wikipedia org wiki ISO 4217货币 有 6 行 ID 国家 地区 货币名称 字母代码 数字代码 次要单位 我需要获取一些数据4种最常用的货币 https en wi
  • 错误 C2143:语法错误:缺少 ';'在“输入”之前

    我是 C 编程新手 请告诉我这个程序有什么问题 以及为什么我收到此错误 错误 C2143 语法错误 缺少 在 输入 之前 extern void func int main int argc char argv func int i 1 f
  • cf run-task 运行前需要上传 env/script 吗?一种优雅的方式?

    我正在与 Cloud Foundry 合作 My need是在我的应用程序之外运行数据库迁移 以便我可以在需要时以某种方式 cf 命令 api 调用等 触发迁移 我被推荐使用cf run task 经过检查 我的理解是 cf run tas
  • 将 pandas 数据框中每个组的多个列的值折叠成一组的 pythonic 方法是什么?

    给定一个数据框 将列的每组值折叠为一组很简单 df groupby A B apply set 但是 如果您想在多个列上执行此操作并且结果位于数据框中 那么如何以Pythonic方式执行此操作呢 例如对于以下数据框 import panda
  • VS code中Monokai Pro主题的大写颜色问题

    在Monokai Pro颜色主题中 我的一些以大写开头的参数显示为紫色 例如 DP piping 如下所示 有什么方法可以将其恢复为白色 就像我的其他参数一样 我尝试切换到另一个主题 但其他主题对我来说不舒服或有相同的问题 任何变量之前有超
  • -[UITableViewDelegate willDisplayCell:forRowAtIndexPath:] 是什么?

    在我所有的UITableView编程时 我总是配置我的UITableViewCells in UITableViewDataSource tableView cellForRowAtIndexPath 现在我遇到了 UITableViewD
  • 使用 Jest 和 Enzyme 测试 FaC 时未找到 React Node 节点

    我正在 React Native 中构建一个应用程序 我们最近开始在应用程序中使用 TypeScript 我的任务是迁移单元测试 有一项测试奇迹般地失败了 该应用程序有一个