如果 TextInput 等于“”,我想测试用户不应该导航到任何其他屏幕。
我试图让控制台日志更正确地理解,但现在的问题是,在input.simulate("changeText", "any@email.com");
正确发生之后,控制台日志说来自测试的传入值是“any@email.com”,但是在setValue(text);
发生之后,console.log 说 useState 值是“ ”。
为什么状态没有改变?我需要用 更新包装器.update()
吗?
这是我的 React Native 代码:
import React, { useState } from "react";
import { View, Button, TextInput } from "react-native";
export const LoginContainer = (props) => {
const [value, setValue] = useState("");
const handleClick = () => {
if (value !== "") {
props.navigation.navigate("any other screen");
}
}
return (
<View>
<TextInput
test-id="login-input"
onChangeText={(text) => {
console.log("INPUT_TEXT:", text);
setValue(text);
console.log("STATE_TEXT:", value);
}}
value={value}
/>
<Button test-id="login-button" onPress={() => handleClick()} />
</View>
);
}
控制台日志:
console.log
INPUT_TEXT: any@email.com
at onChangeText (....)
console.log
STATE_TEXT:
at onChangeText (....)
expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
测试代码:
import "react-native";
import React from "react";
import { shallow } from 'enzyme';
import { LoginContainer } from "...";
import { findByTestAttr } from '...';
const navigation = {
navigate: jest.fn()
}
describe('correct login action', () => {
const wrapper = shallow(<LoginContainer navigation={navigation} />);
let input = findByTestAttr(wrapper, "login-input");
let button = findByTestAttr(wrapper, "login-button");
test('should not navigate to login mail screen if email adress is not entered', () => {
input.simulate("changeText", "any@email.com");
button.simulate("press");
expect(navigation.navigate).toHaveBeenCalledTimes(1);
//input.simulate("changeText", "");
//button.simulate("press");
//expect(navigation.navigate).toHaveBeenCalledTimes(0);
});
});