问题描述
我正在尝试测试组件中的功能,基本思想是设置了某种状态,并且当按下按钮时,会以设置状态调用一个函数.该代码有效,但是当我尝试对此进行测试时,却没有得到预期的结果,就像在测试期间从未设置状态一样.
I am trying to test functionality in my component, the basic idea is some state is set and when a button is pressed a function is called with the set state. The code works but when I try to test this I don't get the expected result, it is as if the state never gets set during the test.
我正在用Jest和Enzyme测试过的React Native应用程序中使用带有钩子(useState)的功能组件.
I am using a functional component with hooks (useState) in a React Native app tested with Jest and Enzyme.
一个重复我的问题的例子是:
An example which replicates my problem is:
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");
});
});
任何对我做错事/失踪的帮助都是很好的.
Any help on what I am doing wrong/missing would be great.
推荐答案
这里的问题是两件事.首先,在执行操作将导致状态更新后,我需要调用 wrapper.update();
.其次,我需要在执行 wrapper.update();
后再次查找该元素,以使该元素具有更新的状态.
The problem here is 2 things. First I need to call wrapper.update();
after performing actions will cause the state to update. Second I need to find the element again after performing wrapper.update();
for that element to have the updated state.
有效的解决方案是:
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");
});
});
这篇关于在使用React Native和Hooks的Jest测试期间状态没有更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!