首页 > 解决方案 > 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
  );
});

我在哪里嘲笑signInWithEmailAndPasswordjest.fn().

当我运行这个测试时,它失败了:

expect(jest.fn()).toHaveBeenCalledWith(...expected)

Expected: "foo@email.com", "password"
Received: undefined, undefined

我注意到console.log(data)我在我的onSubmit函数中打印出来的:

console.log
  {}

这意味着没有文本被拾取。

我该如何测试这个表格?

标签: jestjsreact-hook-form

解决方案


我认为它为您返回 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 的想法,让我知道它是否有效。


推荐阅读