Jest

  1. 쿼리함수
  2. ESLINT PlugIn
  3. TDD 테스트 주도 개발
  4. FireEvent
  5. query 사용 우선순위
  6. MSW 사용해서 테스트하기

목차

FireEvent API

테스트 대상 컴포넌트


//App.js

function App() {
  const [counter, setCounter] = useState(0);
  return (
    <div className="App">
      <header className="App-header">
        <h3 data-testid="counter">{counter}</h3>
        <div>
          <button data-testid="minus-button">-</button>
          <button
            data-testid="plus-button"
            onClick={() => {
              setCounter(counter + 1);
            }}
          >
            +
          </button>
        </div>
      </header>
    </div>
  );
}

테스트 코드

test("when the + button is pressed, the counter cheanges to 1", () => {
  render(<App />);
  const buttonElement = screen.getByTestId("plus-button");
  fireEvent.click(buttonElement);
  const counterElement = screen.getByTestId("counter");
  expect(counterElement).toHaveTextContent(1);
});
  1. 렌더 대상을 불러온다
  2. 버튼과 카운터 엘레멘트를 불러온다
  3. 버튼에 클릭 이벤트를 더한다
  4. 카운터 엘레멘트가 어떤 변화가 이루어 질지 예측하자.

toHaveStyle (matcher)

<div>
	<button
		data-testid="on/off-button"
		style={{ backgroundColor: "blue" }}
>
on/off
	</button>
</div>
test("on/off button has blue color", () => {
  render(<App />);
  const buttonElement = screen.getByTestId("on/off-button");
  expect(buttonElement).toHaveStyle({ backgroundColor: "blue" });
});

toBeDisabled