react-hook-form 提交不会从玩笑测试中获取 changeText

react-hook-form submit does not pick up changeText from jest test

我有以下 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>

我正在以下测试中使用 jest 测试对 firebase.auth().signInWithEmailAndPassword 的提交和调用:

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

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

console.log
  {}

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

我该如何测试这个表格?

我认为它 returns 未定义的原因是您试图以同步方式测试异步行为。我建议在 onSubmit 方法中使用 Promises 来等待 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);
    });
};

这将确保您正在等待登录。

在你的测试中,我会将 firebase 模拟成这样

jest.mock('firebase', () => ({
    auth: jest.fn().mockReturnThis(),
    signInWithEmailAndPassword: jest.fn(),
   })
);

然后在您的测试中,您还需要使用 waitFor() 等待登录发生,然后您可以检查您的结果。像这样的东西可以工作

await waitFor(() => expect(firebase.auth().signInWithEmailAndPassword).toHaveBeenCalledWith(
    email,
    password
  ););

我自己没有测试过,但尝试使用异步和 Promises 的想法,如果可行请告诉我。