Я пытаюсь проверить функциональность своего компонента, основная идея заключается в том, что какое-то состояние установлено, и при нажатии кнопки вызывается функция с установленным состоянием. Код работает, но когда я пытаюсь проверить это, я не получаю ожидаемого результата, как будто состояние никогда не устанавливается во время теста.
Я использую функциональный компонент с хуками (useState) в приложении React Native, протестированном с помощью Jest и Enzyme.
Пример, который повторяет мою проблему:
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");
});
});
Любая помощь в том, что я делаю неправильно/отсутствует, была бы отличной.
Проблема здесь в 2 вещах. Сначала мне нужно вызвать 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()
, но мне нужно было снова найти элемент.
Этот ответ было трудно найти нелепо!