Ric*_*ard 5 jestjs react-hook-form
我有以下几点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>
Run Code Online (Sandbox Code Playgroud)
我正在测试提交和调用firebase.auth().signInWithEmailAndPassword
usingjest
在以下测试中:
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
);
});
Run Code Online (Sandbox Code Playgroud)
我已经将其模拟signInWithEmailAndPassword
为jest.fn()
.
当我运行这个测试时,它失败了:
expect(jest.fn()).toHaveBeenCalledWith(...expected)
Expected: "foo@email.com", "password"
Received: undefined, undefined
Run Code Online (Sandbox Code Playgroud)
我注意到console.log(data)
我在我的onSubmit
函数中打印出了:
console.log
{}
Run Code Online (Sandbox Code Playgroud)
这意味着没有选择文本。
我该如何测试这个表格?
我认为它为您返回未定义的原因是您正在尝试以同步方式测试异步行为。我建议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);
});
};
Run Code Online (Sandbox Code Playgroud)
这将确保您正在等待登录发生。
在你的测试中,我会将 firebase 模拟成这样
jest.mock('firebase', () => ({
auth: jest.fn().mockReturnThis(),
signInWithEmailAndPassword: jest.fn(),
})
);
Run Code Online (Sandbox Code Playgroud)
然后在测试中,您还需要等待waitFor()
登录发生,以便检查结果。像这样的东西可以工作
await waitFor(() => expect(firebase.auth().signInWithEmailAndPassword).toHaveBeenCalledWith(
email,
password
););
Run Code Online (Sandbox Code Playgroud)
我自己还没有测试过,但尝试使用异步和 Promises 的想法,并让我知道这是否有效。
归档时间: |
|
查看次数: |
209 次 |
最近记录: |