8장 좋은 리액트 코드 작성을 위한 환경 구축하기

8.2 리액트 팀이 권장하는 리액트 테스트 라이브러리

8.2.1 React Testing Library란?

const jsdom = require('jsdom')
const { JSDOM } = jsdom
const dom = new JSDOM('<!DOCTYPE html><p>Hello world</p>')
console.log(dom.window.docuinent.querySelector('p').textcontent) // "Hello world"

8.2.2 자바스크립트테스트의기초

function sum(a, b) {
    return a + b
}
// 테스트 1
// 함수를 실행했을 때의 실제 결과
let actual = suin(l, 2)
// 함수를 실행했을 때 기대하는 결과
let expected = 3
if (expected != actual) {
    throw new Error('${expected} is not equal to ${actual}')
}
// 테스트 2
actual = sum(2, 2)
expected = 4
if (expected !== actual) {
    throw new Error('${expected} is not equal to ${actual}')
}
const assert = require('assert')
function suni(a, b) {
    return a + b
}
assert.equal(sum(l, 2), 3)
assert.equal(sum(2, 2), 4)
assert.equal(sum(l, 2), 4) // AssertionError [ERR_ASSERTION] [ERR_ASSERTION]: 3

const { sum } = require('./math')

test('두 인수가 덧셈이 되어야 한다.', () => {
    expect(sum(l, 2)).toBe(3)
})
test('두 인수가 덧셈이 되어야 한다.', () => {
    expect(sum(2, 2)).toBe(3) // 에러
})

8.2.3 리액트컴포넌트테스트 코드 작성하기

프로젝트 생성
npx create-react-app react-test --template typescript
import React from 'react'
import { render, screen } from '©testing-library/react'
import App from './App'
test('renders learn react link', () => {
    render(<App />)
    const linkElement = screen.getByText(/learn react/i)
    expect(linkElement).toBeInTheDocument()
})
import React from 'react'
import logo from './logo.svg'
import './App.css'
function App() {
    return (
        <div className="App">
            <header className= "App-header">
                <img src={logo} className="App-logo" alt="logo" />
                <p>
                    Edit <code>src/App.tsx</code> and save to reload.
                </p>
                <a
                    className="App-link"
                    href="https://react]s.org"
                    target="_blank"
                    rel="noopener noreferrer"
                    >
                    Learn React
                </a>
            </header>
        </div>
    )
}
export default App
정적 컴포넌트
동적 컴포넌트
사용자가 usestate를 통해 입력을 변경하는 컴포넌트
const setup =()=>{
    const screen = render(<InputComponent />)
    const input = screen.getByLabelText('input') as HTMLInputElement
    const button = screen.getByText(/제출하기/i) as HTMLButtonElement
    return {
        input,
        button.
        ...screen.
    }
}
const calc = {
    add: (a, b) => a + b,
}
const spyFn = jest.spyOn(calc, 'add')
const result = calc.add(l, 2)
expect(spyFn).toBeCalledTimes(l)
expect(spyFn).toBeCalledWith(l, 2)
expect(result).toBe(3)

8.2.5 테스트를 작성하기에앞서고려해야 할 점

8.2.6 그 밖에 해볼 만한 여러 가지 테스트

8.2.7 정리

끝!