본문 바로가기

FrontEnd

[Vite, Vitest, Javascript] Vanilla JS로 TDD with Vitest

반응형

프로그래머스 과제관의 Vanilla SPA 연습에 TDD를 적용하면서 배운 방법을 공유한다.

 

How to Unit Test HTML and Vanilla JavaScript Without a UI Framework

Recently I was curious about something: Is it possible to write unit tests for front end code that do...

dev.to


1. index.html 만들기

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>바닐라 TDD</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/main.js"></script>
  </body>
</html>

2. 필요한 라이브러리 다운받기

yarn add -D @testing-library/dom @testing-library/jest-dom jsdom jest

3. Vitest 설정하기

vite.config,js 설정을 추가한다.

export default defineConfig({
  test: {
    environment: "jsdom", // or 'jsdom', 'node'
  },
});

4. 반드시 실패하는 테스트를 먼저 작성한다.

vitest의 expect에 jest-dom matcher를 추가한다.

import { getByText, screen } from "@testing-library/dom";
import matchers from "@testing-library/jest-dom/matchers";
import { beforeEach, describe, expect, it } from "vitest";
// extends Vitest's expect method with methods from react-testing-library
expect.extend(matchers);

import Heading from "src/components/Heading";
let container;

describe("Heading.js", () => {
  beforeEach(() => {
    container = document.body;
  });

  it("renders title", () => {
    const title = "Hello world";
    Heading({ $target: document.body, initialState: { title } });
    expect(getByText(document.body, title)).toBeInTheDocument();
    // screen.debug();
  });
});

그 다음 테스트를 실행한뒤 실패한다. (yarn test)

5. 테스트를 통과하는 컴포넌트를 작성한다.

Heading.js

/**
 * @typedef {{title:string}} State
 * @param {{$target :HTMLElement,initialState:State }} param
 */
export default function Heading({ $target, initialState }) {
  const $Heading = document.createElement("h1");
  $target.appendChild($Heading);

  function render() {
    $Heading.innerHTML = `${initialState.title}`;
  }
  render();
}

6. 테스트를 통과한다.

테스트 통과

다음 적절히 리팩토링 한다.


참고

https://dev.to/thawkin3/how-to-unit-test-html-and-vanilla-javascript-without-a-ui-framework-4io

 

How to Unit Test HTML and Vanilla JavaScript Without a UI Framework

Recently I was curious about something: Is it possible to write unit tests for front end code that do...

dev.to

https://testing-library.com/docs/queries/about

 

About Queries | Testing Library

Overview

testing-library.com

https://www.robinwieruch.de/vitest-react-testing-library/

 

Vitest with React Testing Library

Learn how to use React Testing Library with Vitest in Vite. React Testing Library is a popular testing library for writing tests in React applications ...

www.robinwieruch.de

 

반응형