0

尝试使用 react-testing-library 编写我的第一个测试,但它似乎无法获取正确的 material-ui 元素。

https://codesandbox.io/s/lx5nl1839z

我收到错误消息说该事件从未被触发。

预期的模拟函数被调用了一次,但它被调用了零次。

当我将button材料 ui 中的 Button 更改为常规按钮而不是 Button 时,它就可以工作了。

这是我的测试

test('calls with user email and password', () => {
  const login = jest.fn();
  const error = null as any;

  const { getByLabelText, getByText } = render(
    <LoginForm login={login} error={error} />
  );

  const email = getByLabelText('Email');
  const password = getByLabelText('Password');
  (email as any).value = 'leoq91@gmail.com';
  (password as any).value = 'password';
  fireEvent.click(getByText('Login'));


  expect(login).toHaveBeenCalledTimes(1);
  expect(login).toHaveBeenCalledWith({
      email: 'leoq91@gmail.com',
      password: 'password',
  });
});

这是我的组件:

export const LoginForm: FunctionComponent<IProps> = ({ login, error }) => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  return (
    <Paper style={{ width: '400px', padding: '30px', margin: '0 auto' }}>
      <form
        onSubmit={e => {
          e.preventDefault();
          return login({ email, password });
        }}
      >
        <TextField
          id="email"
          label="Email"
          onChange={e => setEmail(e.target.value)}
          fullWidth
          variant="outlined"
          error={Boolean(getEmailError(email))}
          helperText={getEmailError(email)}
        />
        <TextField
          id="password"
          label="Password"
          type="password"
          style={{ marginTop: '10px' }}
          onChange={e => setPassword(e.target.value)}
          fullWidth
          variant="outlined"
        />
        <LoginError error={error} />
        <Button
          variant="contained"
          color="primary"
          type="submit"
          fullWidth
          // disabled={isDisabled(email, password)}
          style={{
            margin: '20px 0px',
          }}
        >
          Login
        </Button>
      </form>
      <Divider />
      <Typography style={{ margin: '10px auto' }}>Forgot password?</Typography>
    </Paper>
  );
};
4

4 回答 4

1

首先,codeandbox 不可靠……

Codesandbox 以某种方式在浏览器中而不是在 jsdom 中运行测试。

这是问题所在: https ://github.com/kentcdodds/react-testing-library/issues/234

要点是因为它是单击submit跨度,而不是按钮。它应该冒泡,但事实并非如此。

这是一个使用 Typescript 的本地服务器的工作示例。

test('calls with user email and password', () => {
    const login = jest.fn();

    const { getByLabelText, container } = render(
      <LoginForm login={login} error={null} />
    );

    const emailNode = getByLabelText('Email');
    const passwordNode = getByLabelText('Password');

    if (
      emailNode instanceof HTMLInputElement &&
      passwordNode instanceof HTMLInputElement
    ) {
      fireEvent.change(emailNode, { target: { value: 'leoq91@gmail.com' } });
      fireEvent.change(passwordNode, { target: { value: 'password' } });
      const form = container.querySelector('form') as HTMLFormElement;
      form.dispatchEvent(new Event('submit'));
      expect(login).toHaveBeenCalledTimes(1);
      expect(login).toHaveBeenCalledWith({
        email: emailNode.value,
        password: passwordNode.value,
      });
    } else {
      expect(false);
    }
  });
于 2018-12-07T06:24:50.973 回答
0

我已经为此考虑了一段时间,最后得到了一些东西来将 data-testid 放在输入上,而不是在它周围的 div 上,它构成了 material-ui 中的 TextField。

您应该data-testid像这样在 inputProps 中设置:

<TextField
     type="password"
     variant="outlined"
     required
     value={password}
     onChange={onChangePassword}
     inputProps={{
         'data-testid': 'testPassword'
     }}
 />

然后您可以像这样在测试中访问它并模拟新的用户输入:

const passwordInput = getByTestId('testPassword');
fireEvent.change(passwordInput, { target: { value: VALID_PASSWORD } });
于 2021-02-15T23:13:56.977 回答
0

您的 TextFields 不受控制。您应该传递实际值并在更改事件中设置实际值。您当前在测试中两次触发提交。

使用这些修复程序运行测试具有正确的控制台输出,但由于某种原因,codesandbox 忽略了笑话匹配器。我不知道那里发生了什么,但通过上述修复,它的要点是有效的。

于 2018-12-07T06:18:48.790 回答
-2

我看到很多人对 material-ui 有问题。我的猜测是Button试图做一些花哨的事情并破坏正常的 HTML 事件流。

我的建议是使用jest.mock()和 mockButton来渲染 a button

于 2018-12-06T07:38:53.160 回答