>我正在尝试测试组件中的功能,基本思想是设置某种状态,当按下按钮时,会调用具有设置状态的函数。代码有效,但是当我尝试测试它时,我没有得到预期的结果,就好像在测试期间从未设置过状态一样。
我正在使用带有钩子的功能组件(useState(在用Jest和Enzyme测试的React Native应用程序中。
复制我的问题的一个例子是:
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");
});
});
任何关于我做错/缺失的帮助都会很棒。
这里的问题是两件事。首先我需要调用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");
});
});