Testing

Bin2·2022년 7월 26일
0

auto complete

npm i -D @types/jest
// jsconfig.json

{
  "typeAcquisition": {
    "include": ["jest"]
  }
}

coverage

npm run test -- --coverage

unit test

describe(('테스트') => {
	let update;

	// test가 실행되기 전에 beforeEach의 코드가 실행됨.
	beforeEach(() => {
		update = jest.fn(); // mock 함수
	})
  
  	it(('테스트') => {
    	expect().toBe() // 값의 비교
      	expect().toEqual() // 참조값이 달라도 값의 비교 가능
      	expect().toHaveBeenCalledTimes() // 함수의 호출 횟수
      	expect().toHaveBeenCalledWith(arg1, arg2) // 인자의 비교
      	expect(() => callback()).toThrow() // 함수 실행 중 에러 확인 (실행 도중 발생하기 때문에 콜백 함수의 형태)
    })
})


component test

import React from "react";
import { render, screen } from "@testing-library/react";
import HabitAddForm from "../habitAddForm";
import userEvent from "@testing-library/user-event";


describe("HabitAddForm", () => {
    let onAdd;
    let input;
    let button;
    beforeEach(() => {
      onAdd = jest.fn();
      input = screen.getByPlaceholderText("Habit");
      button = screen.getByText("Add");
      render(<HabitAddForm onAdd={onAdd} />);
    });

    it("calls onAdd when button is clicked and valid habit is entered", () => {
      // userEvent.click(button);
      fireEvent.click(screen.getByTitle('add')) // tag 에 title을 추가하여 해당 요소에 접근할 수 있음.
      fireEvent.click(screen.getAllByTitle("reset")[0]); // All 사용할 경우 [0]
      fireEvent.change(input, { target: { value: "hi" } });
      
      expect(onAdd).toHaveBeenCalledWith("New Habit");
      expect(onAdd).toHaveBeenCalledTimes(1);
      
      const addedCount = screen.getAllByTestId("habit-count")[3]; // tag에 data-testid 추가
      expect(addedCount.innerHTML).toBe("0");
      expect().toBeInTheDocument();
    });
});

snapshot test

import renderer from "react-test-renderer";

  test("renders", () => {
    // 스냅샷 테스트
    // update 시 npm run test -- -u
    const component = renderer.create(<HabitAddForm onAdd={jest.fn()} />);
    expect(component.toJSON()).toMatchSnapshot();
  });
profile
Developer

0개의 댓글