jtwjs Dev Wiki
  • DEV_ROAD
    • 💪🏻 생존하기
    • Week 1
      • 개발 환경 세팅
      • 타입스크립트
      • 리엑트
      • Testing Library
      • Parcel & ESLint
    • Week 2
      • JSX
      • Virtual DOM
    • Week 3
      • React Component
      • React State
    • Week 4
      • Express
      • Fetch API & CORS
      • React Hook
      • useRef & Custom Hook
    • Week 5
      • TDD
      • React Testing Library
      • MSW
      • Playwrite
      • Snapshot
    • Week 6
      • Separtion of Concerns
      • Principle
      • DI, (Dependency Injection)
      • Reflect-metadata
      • TSyringe
      • External Store
      • Follow Redux
      • usestore-ts
      • useSyncExternalStore
    • Week 7
      • Routing
      • Routes
      • Router
      • Navigation
    • Week 8
      • Design System
      • Style Basics
      • CSS-in-JS
      • Styled-Components
      • Global Style & Theme
    • Week 9
      • 개발하기 전 준비
      • 상품 목록 페이지
      • 상품 상세 페이지
      • 장바구니 페이지
    • Week 10
      • 로그인
      • 로그아웃
      • 회원가입
      • 주문 목록 & 주문 상세
    • Week 11
      • 배송 정보 입력
      • 포트원 결제 요청
      • 배송 및 결제 정보 전달
    • Week 12
      • 관리자 웹사이트개발시작
  • DEV_NOTE
    • TypeScript
      • 기본적 문법
        • Enum
        • 다형성
          • Untitled
        • 구조적 타이핑
        • 제너릭 타입
        • 컨디셔널 타입
        • 함수 메서드 타이핑
        • infer로 타입스크립트의 추론 직접 활용
        • 재귀 타입
        • 템플릿 리터럴 타입
        • 추가적인 타입 검사 satisfies 연산자
        • 타입스크립트 건망증
        • 원시 자료형에도 브랜딩 기법 사용 가능
        • 타입 좁히기
        • 유용한 타입 만들기
        • 데코레이터 함수
        • 앰비언트 선언도 선언 병합이 된다.
        • 앰비언트 선언도 선언병합이 된다.
    • Testing
      • Unit Testing
      • 단위 테스트의 두 분파
      • 좋은 단위 테스트를 구성하는 4대 요소
      • 테스트 대역과 식별할 수 있는 동작
      • 단위 테스트 스타일
      • 가치 있는 단위 테스트를 위한 리팩토링
      • 통합 테스트
      • Cross Browsing Testing
      • 기능 테스트 종류
      • React Testing Pattern
      • 프론트엔드 테스트 입문
        • 테스트 범위
        • 단위 테스트 검증
        • Mock
        • UI 컴포넌트 테스트
        • 테스트 커버리지
        • 웹 통합 테스트
        • MSW
        • 스토리북
        • 시각적 회귀 테스트
        • E2E 테스트
        • Github Actions 설정
        • 깃허브 액션에서 E2E
      • 시프트 레프트
        • 테스트 기본중의 기본
        • 단위 테스트
        • 코드 복잡도
        • 리팩터링
        • 코드 리뷰
        • 통합 테스트 패턴
        • 시스템 테스트의 자동화
        • 탐색적 테스트
      • Test Tip
      • vitest
      • playwright
      • Test Data Generator
      • MSW
    • Algorithm
      • coding test
      • Data Structure
    • Next.js
      • Data Fetching
      • Hydration
      • Next 13
      • Optimization
      • Next 15
    • Tailwind
      • Tailwind CSS
      • Theme
      • Directives
      • Tool
      • Design System
    • Storybook
      • Storybook
      • CSF3
      • CDD
      • Headless Component
    • Funtional Programming
      • 함수형 프로그래밍
      • 참조 투명성
      • 부수효과
      • 함수 합성
      • 제너릭 타입 활용하기
      • 암묵적 입출력
      • 액션과 계산, 데이터
      • 계층형 설계
      • 호출 그래프
      • 함수형 설계
      • 불변성
      • 일급 함수
      • 함수형 도구
    • Git
      • Github Actions
      • Conflict
      • Branch 전략
    • Contents Format
      • Audio
    • 3D Graphic
      • 3D keyword
      • Three.js
      • Geometry
      • Material
      • Light
      • Camera
      • Decal
      • Rotation
      • Text
      • Shadow
      • Fog
      • Post Processing
      • Animation
      • Math
        • Vector Space
        • 벡터의 연산
        • 회전 계산
      • 3D 컨텐츠가 만들어지는 과정
      • R3F
      • Env
      • Scene
      • Transform
      • R3F
      • Interaction & Raycast
      • Rendering Algorithnm
      • Blender
      • Blender
    • Accessibility
      • 접근성이란
    • Interactive Web
      • Parallax
      • Canvas
      • requestAnimationFrame
      • Effect
      • HSL
      • React.js + Canvas
      • Matter.js
    • AWS
      • DevOps
      • Amplify
      • S3
      • 클라우드 컴퓨팅
        • 온프레미스와 클라우드
        • 클라우드 도입효과
        • 클라우드 컴퓨팅의 범위
        • 컴퓨팅 옵션
          • EC2 - Virtual Machin
          • ECS, EKS - Container
          • Lambda - Serverless
        • 네트워크 가상화
        • 스토리지
        • 데이터베이스
        • 데이터 수집
        • 머신 러닝 영역
        • IoT 영역
        • 블록체인 영역
      • 클라우드 아키텍처 설계
    • Network
      • Web Server & WAS
    • System Design
      • System Design
      • Component
      • 의존성을 배제한 개발
      • Error Handling
      • Architecture
        • 모노로틱 아키텍처
        • Clean Architecture
        • Layered Architecture
        • 이벤트 기반 아키텍처
      • 상황을 파악하는 메타인지
      • 중복 문제 해결하기
      • Monorepo Arhitecture
        • 모노레포 운영과 트러블슈팅
        • Module Federation
      • 코드 병목지점
      • API 대응
      • 공통 코드
      • Infra 구축
      • 모듈 기반의 개발 방식
      • Design System
        • 최소 수준의 아키텍처 설정
        • 더 효율적인 디자인시스템 만들기
        • 디자인 시스템과 UI 라이브러리 목적
        • 디자인 토큰
      • 효율적인 업무
        • 업무 프로세스 병목 파악
      • Clean Code
      • Design Pattern
        • CQRS Pattern
        • Strangler Fig Pattern
        • 데코레이터 패턴
        • 커맨드 패턴
        • 전략 패턴
        • 옵저버 패턴
      • A/B 테스팅
      • 대규모 리엑트 웹앱 개발
        • 복잡성 관리
        • 모듈성
        • 성능
        • 디자인 시스템
        • 데이터 패칭
        • 상태 관리
        • 국제화
        • 코드 조직화하기
        • 개인화 A/B 테스팅
        • 확장 가능한 웹 아키텍처
        • 테스팅
        • 툴링
        • 기술적 마이그레이션
        • 타입스크립트
        • 라우팅
        • 사용자 중심 API 디자인
        • 리액트 미래
    • Performance
      • React DevTools
      • Component 최적화
      • Page Load
      • API
    • MFA
      • MSA
      • MFA 도입하기
      • Monorepo
        • Monorepo Tool
        • Yarn Berry Workspace
        • Turborepo
      • MFA Composition
      • SPA 통합
      • Design System
      • Package Manager
        • Yarn
        • pnpm
      • Transpiler & Bundler
        • Babel
        • Rollup
        • esbuild
        • swc
        • Webpack
        • Vite
      • 분해와 통합을 위한 여러 기술 비교
    • State Management
      • Zustand
    • React v18
      • Automatic batching
      • Suspense
      • Transition
    • SEO
      • Search Engine Optimization
      • Open Graph Element
      • Metadata
    • FE Develop
      • Scrubbing
      • Clipboard
    • Refactoring
      • 리팩토링 깊게 들여다보기
      • 긴 코드 조각내기
      • 타입 코드 처리하기
      • 유사한 코드 융합하기
      • 데이터 보호
      • 코드 추가 및 제거
    • OAuth 2.0
    • Analytics
      • Mixpanel
    • ETC
      • VSCode
    • React Hook In Action
      • useContext & Provider
      • 커스텀 훅
      • 코드 분할하기 with Suspense, lazy
      • Suspense와 이미지 적재하기
      • useTransition, uesDeferredValue
      • SuspenseList
Powered by GitBook
On this page
  • 회원가입 기능
  • User Scenario
  1. DEV_ROAD
  2. Week 10

회원가입

회원가입 기능

User Scenario

  • 이메일, 이름, 패스워드를 입력하여 회원가입을 한다.

  • 필드 값이 유효성에 어긋날시 에러 메시지가 노출된다.

  • 유효성에 어긋나거나 값이 채워지지 않은 경우 회원가입 버튼은 Disabled 상태가 된다.

  • 회원가입에 성공하면 회원가입 성공 페이지로 이동된다.

  • 회원가입 성공시 로그인 상태가 된다.

Unit Test

SignupForm.test.tsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Route } from "react-router-dom";

import VALID_MSG from "@/constants/validMsg";
import { withAllContexts, withRouter } from "@/tests/utils";

import SignupForm from "./SignupForm";

const context = describe;

describe("SignupForm", () => {
  function renderSignupForm() {
    return render(
      withAllContexts(withRouter(<Route path="/" element={<SignupForm />} />))
    );
  }

  it("render correctly", () => {
    renderSignupForm();

    expect(screen.getByRole("textbox", { name: "E-mail" })).toBeInTheDocument();
    expect(screen.getByRole("textbox", { name: "Name" })).toBeInTheDocument();
    expect(screen.getByLabelText("Password")).toBeInTheDocument();
    expect(screen.getByLabelText("Password Confirm")).toBeInTheDocument();
    expect(screen.getByRole("button", { name: "회원가입" }));
  });

  context("when email value is invalid", () => {
    it(`display error message "${VALID_MSG.EMAIL}"`, async () => {
      renderSignupForm();

      const emailInput = screen.getByRole("textbox", { name: "E-mail" });
      await userEvent.type(emailInput, "xxxxxxx");

      expect(emailInput).toHaveValue("xxxxxxx");
      expect(screen.getByText(VALID_MSG.EMAIL)).toBeInTheDocument();
    });

    it("submit button is disabled", async () => {
      renderSignupForm();

      const emailInput = screen.getByRole("textbox", { name: "E-mail" });
      await userEvent.type(emailInput, "xxxxxxx");

      expect(screen.getByRole("button", { name: "회원가입" })).toBeDisabled();
    });
  });

  context("when name value is invalid", () => {
    it(`display error message "${VALID_MSG.NAME}"`, async () => {
      renderSignupForm();

      const nameInput = screen.getByRole("textbox", { name: "Name" });
      await userEvent.type(nameInput, "xxxxxxx");

      expect(nameInput).toHaveValue("xxxxxxx");
      expect(screen.getByText(VALID_MSG.NAME)).toBeInTheDocument();
    });

    it("submit button is disabled", async () => {
      renderSignupForm();

      const nameInput = screen.getByRole("textbox", { name: "Name" });
      await userEvent.type(nameInput, "xxxxxxx");

      expect(screen.getByRole("button", { name: "회원가입" })).toBeDisabled();
    });
  });

  context("when password value is invalid", () => {
    it(`display error message "${VALID_MSG.PASSWORD}"`, async () => {
      renderSignupForm();

      const passwordInput = screen.getByLabelText("Password");
      await userEvent.type(passwordInput, "123123");

      expect(passwordInput).toHaveValue("123123");
      expect(screen.getByText(VALID_MSG.PASSWORD)).toBeInTheDocument();
    });

    it("submit button is disabled", async () => {
      renderSignupForm();

      const passwordInput = screen.getByLabelText("Password");
      await userEvent.type(passwordInput, "123123");

      expect(screen.getByRole("button", { name: "회원가입" })).toBeDisabled();
    });
  });

  context("when password confirm value is invalid", () => {
    it(`display error message "${VALID_MSG.PASSWORD_C}"`, async () => {
      renderSignupForm();
      await userEvent.type(screen.getByLabelText("Password"), "password");

      const passwordConfirmInput = screen.getByLabelText("Password Confirm");
      await userEvent.type(passwordConfirmInput, "pass");

      expect(passwordConfirmInput).toHaveValue("pass");
      expect(screen.getByText(VALID_MSG.PASSWORD_C)).toBeInTheDocument();
    });

    it("submit button is disabled", async () => {
      renderSignupForm();

      await userEvent.type(screen.getByLabelText("Password"), "password");
      await userEvent.type(screen.getByLabelText("Password Confirm"), "pass");

      expect(screen.getByRole("button", { name: "회원가입" })).toBeDisabled();
    });
  });

  context("when the form is empty", () => {
    it("submit button is disabled", async () => {
      renderSignupForm();

      expect(screen.getByRole("button", { name: "회원가입" })).toBeDisabled();
    });
  });
});

SignupFormStore.test.ts

import VALID_MSG from "@/constants/validMsg";

import SignupFormStore from "./SignupFormStore";

const context = describe;

describe("SignupFormStore", () => {
  let store: SignupFormStore;

  beforeEach(() => {
    store = new SignupFormStore();
  });

  describe("change email", () => {
    it("email is changed", () => {
      const email = "v_oyb@naver.com";
      store.changeEmail(email);

      expect(store.email).toBe(email);
    });

    context("when value is invalid", () => {
      it(`error is ${VALID_MSG.EMAIL}`, () => {
        store.changeEmail("invalid email");

        expect(store.error).toBe(VALID_MSG.EMAIL);
      });
    });

    context("when value is valid", () => {
      it("error is empty", () => {
        store.changeEmail("tester@example.com");

        expect(store.error).toBeFalsy();
      });
    });
  });

  describe("change name", () => {
    it("name is changed", () => {
      const name = "정태웅";
      store.changeName(name);

      expect(store.name).toBe(name);
    });

    context("when value is invalid", () => {
      it(`error is ${VALID_MSG.NAME}`, () => {
        store.changeName("invalid name");

        expect(store.error).toBe(VALID_MSG.NAME);
      });
    });

    context("when value is valid", () => {
      it("error is empty", () => {
        store.changeName("정태웅");

        expect(store.error).toBeFalsy();
      });
    });
  });

  describe("change password", () => {
    it("password is changed", () => {
      const password = "password";
      store.changePassword(password);

      expect(store.password).toBe(password);
    });

    context("when value is invalid", () => {
      it(`error is ${VALID_MSG.PASSWORD}`, () => {
        store.changePassword("123123");

        expect(store.error).toBe(VALID_MSG.PASSWORD);
      });
    });

    context("when value is valid", () => {
      it("error is empty", () => {
        store.changePassword("password");

        expect(store.error).toBeFalsy();
      });
    });
  });

  describe("change password confirm", () => {
    it("password confirm value is changed", () => {
      const password = "password";
      store.changePasswordConfirm(password);

      expect(store.passwordConfirm).toBe(password);
    });

    context("when password entered doesn't match", () => {
      it(`error is ${VALID_MSG.PASSWORD_C}`, () => {
        store.changePassword("password");
        store.changePasswordConfirm("password1");

        expect(store.error).toBe(VALID_MSG.PASSWORD_C);
      });
    });

    context("when value is valid", () => {
      it("error is empty", () => {
        store.changePassword("password");
        store.changePasswordConfirm("password");

        expect(store.error).toBeFalsy();
      });
    });
  });

  describe("with reset", () => {
    it("all field values are initialized", () => {
      store.changeEmail("tester@example.com");
      store.changeName("tester");
      store.changePassword("password");
      store.changePasswordConfirm("password");

      store.reset();

      expect(store.email).toBeFalsy();
      expect(store.name).toBeFalsy();
      expect(store.password).toBeFalsy();
      expect(store.passwordConfirm).toBeFalsy();
    });
  });
});
E2E Test
/// <reference types="cypress" />

// 이메일, 이름, 패스워드를 입력하여 회원가입을 한다.
// 필드 값이 유효성에 어긋날시 에러 메시지가 노출된다.
// 유효성에 어긋나거나 값이 채워지지 않은 경우 회원가입 버튼은 Disabled 상태가 된다.
// 회원가입에 성공하면 회원가입 성공 페이지로 이동된다.
// 회원가입에 성공시 로그인 상태가 된다.

describe("Signup", () => {
  beforeEach(() => {
    cy.backdoor();
    cy.visit("/signup");
  });

  context("when form values are invalid", () => {
    it("unable to signup", () => {
      cy.findByRole("textbox", { name: "E-mail" }).type("invalid email");
      cy.findByText("이메일 형식이 올바르지 않습니다.").should("exist");

      cy.findByRole("textbox", { name: "Name" }).type("invalid name");
      cy.findByText("이름 형식이 올바르지 않습니다.").should("exist");

      cy.findByLabelText("Password").type("invalid password1@");
      cy.findByText("비밀번호 형식이 올바르지 않습니다.").should("exist");

      cy.findByLabelText("Password Confirm").type("invalid password");
      cy.findByText("비밀번호가 일치하지 않습니다.").should("exist");

      cy.findByRole("button", { name: "회원가입" }).should("be.disabled");
    });
  });

  context("when signup succeed ", () => {
    beforeEach(() => {
      cy.findByRole("textbox", { name: "E-mail" }).type("tester2@example.com");
      cy.findByRole("textbox", { name: "Name" }).type("테스터");
      cy.findByLabelText("Password").type("password");
      cy.findByLabelText("Password Confirm").type("password");
      cy.findByRole("button", { name: "회원가입" }).click();
    });
    it("redirected signup complete page", () => {
      cy.findByText(/Signup Complete/).should("exist");
      cy.url().should("include", "/signupComplete");
    });

    it("will be logged in status", () => {
      cy.findByRole("link", { name: "Login" }).should("not.exist");
      cy.findByRole("link", { name: "Cart" }).should("exist");
      cy.findByRole("button", { name: "Logout" }).should("exist");
    });
  });
});
Previous로그아웃Next주문 목록 & 주문 상세

Last updated 1 year ago