【问题标题】:State is not updating during Jest tests when using React Native and Hooks使用 React Native 和 Hooks 时,状态在 Jest 测试期间没有更新
【发布时间】:2019-05-29 04:40:42
【问题描述】:

我正在尝试在我的组件中测试功能,基本思想是设置了一些状态,当按下按钮时,会以设置状态调用函数。该代码有效,但是当我尝试对此进行测试时,我没有得到预期的结果,就好像在测试期间从未设置状态一样。

我在使用 Jest 和 Enzyme 测试的 React Native 应用程序中使用带有钩子 (useState) 的功能组件。

复制我的问题的一个例子是:

import React, { useState } from "react";
import { View, Button } from "react-native";
import { shallow } from "enzyme";

const Example = function({ button2Press }) {
const [name, setName] = useState("");

  return (
    <View>
      <Button title="Button 1" onPress={() => setName("Hello")} />
      <Button title="Button 2" onPress={() => button2Press(name)} />
    </View>
  );
};

describe("Example", () => {
  it("updates the state", () => {
    const button2Press = jest.fn();
    const wrapper = shallow(<Example button2Press={button2Press} />)
    const button1 = wrapper.findWhere(node => node.prop("title") === "Button 1")
                        .first();
    const button2 = wrapper.findWhere(node => node.prop("title") === "Button 2")
                        .first();

    button1.props().onPress();
    button2.props().onPress();

    expect(button2Press).toHaveBeenCalledWith("Hello");
  });
});

任何关于我做错/遗漏的帮助都会很棒。

【问题讨论】:

    标签: reactjs react-native jestjs enzyme react-hooks


    【解决方案1】:

    这里的问题是两件事。首先我需要在执行操作后调用wrapper.update(); 将导致状态更新。其次,我需要在执行wrapper.update(); 后再次找到该元素以使该元素具有更新状态。

    可行的解决方案是:

    import React, { useState } from "react";
    import { View, Button } from "react-native";
    import { shallow } from "enzyme";
    
    const Example = function({ button2Press }) {
    const [name, setName] = useState("");
    
      return (
        <View>
          <Button title="Button 1" onPress={() => setName("Hello")} />
          <Button title="Button 2" onPress={() => button2Press(name)} />
        </View>
      );
    };
    
    describe("Example", () => {
      it("updates the state", () => {
        const button2Press = jest.fn();
        const wrapper = shallow(<Example button2Press={button2Press} />)
        const button1 = wrapper.findWhere(node => node.prop("title") === "Button 1")
                            .first();
        button1.props().onPress();
        wrapper.update(); // <-- Make sure to update after changing the state
    
        const button2 = wrapper.findWhere(node => node.prop("title") === "Button 2")
                            .first(); // <-- Find the next element again after performing update
        button2.props().onPress();
    
        expect(button2Press).toHaveBeenCalledWith("Hello");
      });
    });
    

    【讨论】:

    • 这个答案可笑很难找到!
    • 哇,谢谢!我永远被困在这上面!在我的情况下,我不需要调用wrapper.update(),但我确实需要再次找到该元素。
    猜你喜欢
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 2020-01-25
    • 2020-03-24
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多