jestjs - react-hook-form submit 没有从 jest 测试中获取 changeText
问题描述
我有以下内容react-native-form
:
const { register, handleSubmit, setValue, errors } = useForm();
const onSubmit = (data) => {
console.log(data);
return firebase
.auth()
.signInWithEmailAndPassword(data.email, data.password)
.then((info) => {
console.log(info.additionalUserInfo.profile);
})
.catch((err) => {
console.error(err);
});
};
<View>
<TextInput
placeholder="Email"
testID="email-input"
onChangeText={(t) => setValue("email", t)}
style={styles.loginTextInput}
></TextInput>
<TextInput
secureTextEntry={true}
testID="password-input"
placeholder="Password (min. 8 characters)"
onChangeText={(t) => setValue("password", t)}
style={styles.loginTextInput}
></TextInput>
<TouchableOpacity
onPress={handleSubmit(onSubmit)}
testID={"login-email-button"}
style={[styles.loginButton, styles.loginEmailButton]}
>
<Text style={styles.buttonText}>Login with Email</Text>
</TouchableOpacity>
</View>
我正在以下测试中测试提交和使用firebase.auth().signInWithEmailAndPassword
调用jest
:
test("submit works", async () => {
const { getByPlaceholderText, getByTestId, getByText } = render(
<EmailLogin />
);
const emailInput = getByTestId("email-input");
const passwordInput = getByTestId("password-input");
const submitButton = getByTestId("login-email-button");
const email = "foo@email.com";
const password = "password";
fireEvent.changeText(emailInput, email);
fireEvent.changeText(passwordInput, password);
fireEvent.press(submitButton);
expect(firebase.auth().signInWithEmailAndPassword).toHaveBeenCalledWith(
email,
password
);
});
我在哪里嘲笑signInWithEmailAndPassword
为jest.fn()
.
当我运行这个测试时,它失败了:
expect(jest.fn()).toHaveBeenCalledWith(...expected)
Expected: "foo@email.com", "password"
Received: undefined, undefined
我注意到console.log(data)
我在我的onSubmit
函数中打印出来的:
console.log
{}
这意味着没有文本被拾取。
我该如何测试这个表格?
解决方案
我认为它为您返回 undefined 的原因是您正在尝试以同步方式测试异步行为。我建议Promises
在您的onSubmit
方法中使用以等待firebase auth
呼叫完成。
像这样的东西可以工作
const onSubmit = async (data) => {
console.log(data);
return await firebase
.auth()
.signInWithEmailAndPassword(data.email, data.password)
.then((info) => {
console.log(info.additionalUserInfo.profile);
})
.catch((err) => {
console.error(err);
});
};
这将确保您正在等待登录发生。
在你的测试中,我会将火力基地模拟成这样
jest.mock('firebase', () => ({
auth: jest.fn().mockReturnThis(),
signInWithEmailAndPassword: jest.fn(),
})
);
然后在您的测试中,您还需要使用waitFor()
等待登录发生,然后您可以检查您的结果。像这样的东西可以工作
await waitFor(() => expect(firebase.auth().signInWithEmailAndPassword).toHaveBeenCalledWith(
email,
password
););
我自己没有测试过,但尝试使用 async 和 Promises 的想法,让我知道它是否有效。
推荐阅读
- reactjs - TypeScript:“JSX.IntrinsicElements”类型上不存在属性“图标”
- python - 为什么我的程序不使用指定的代理
- java - 为什么我不能将带有 RestTemplate 的文件发送或 POST 到服务器?
- postman - 在 Postman 中发送请求之前将字段设置为随机数
- powerbi - DAX: Return distinct column values based on other conditions
- javascript - Laravel 在刀片中运行 JavaScript
- r - 在表格中排列显微图像以供发布
- java - 指定的项目文件已经存在?无法导入 Android Studio?
- ios - 如何快速绕过我的应用程序窗口的角落?
- c++ - 在坐标系上找到第三个顶点位置