iT邦幫忙

2021 iThome 鐵人賽

DAY 29
0
Modern Web

我不會測試,所以寫Jest與React Testing Library系列 第 29

Day 29: 倒數前兩天,在加班 等重寫

今天的我有點忙要加班,先貼文字 晚點補

import { FC } from 'react';
import axios from 'axios';
import { Redirect, useHistory } from 'react-router-dom';
import useForm from '@hooks/useForm';
import { LoginWrapper } from './Lobby.style';

export type InputType = {
  account: string;
  password: string;
  rememberMe: boolean;
};

export type ErrorType = Omit<InputType, 'rememberMe'>;

const Lobby: FC = () => {
  const history = useHistory();
  const { handleChange, handleSubmit, values, errors } = useForm({
    initialValues: {
      account: '',
      password: '',
      rememberMe: false
    },
    validation: (values) => {
      const errors = {} as ErrorType;

      if (!values.account) {
        errors.account = '請輸入帳號';
      }

      if (!values.password) {
        errors.password = '請輸入密碼';
      }

      return errors;
    },
    onSubmit: async (values) => {
      const res = await axios.post('http://localhost:3001/login');
      console.log(res, 'res');
      if (res.status === 200) {
        history.push('/rooms');
      }
      // return <Redirect to="/rooms" />;
    }
  });

  return (
    <LoginWrapper>
      <input
        role="account"
        name="account"
        onChange={handleChange}
        value={values.account}
        placeholder="Account"
      />
      {errors?.account && <div style={{ color: 'red' }}>{errors.account}</div>}
      <input
        role="password"
        name="password"
        onChange={handleChange}
        value={values.password}
        placeholder="Password"
      />
      {errors?.password && (
        <div style={{ color: 'red' }}>{errors.password}</div>
      )}
      <label>
        <input
          type="checkbox"
          name="rememberMe"
          onChange={handleChange}
          value={String(values.rememberMe)}
          checked={values.rememberMe}
        />
        Remember Me
      </label>
      <button onClick={handleSubmit}>Login</button>
    </LoginWrapper>
  );
};

export default Lobby;


上一篇
Day 28: 初始化要測試的component
下一篇
Day 30: 給之後的時間
系列文
我不會測試,所以寫Jest與React Testing Library30

尚未有邦友留言

立即登入留言