React Testing Library

React ์ปดํฌ๋„ŒํŠธ๋ฅผ ์‚ฌ์šฉ์ž ์ž…์žฅ์— ๊ฐ€๊น๊ฒŒ ํ…Œ์ŠคํŠธํ•  ์ˆ˜ ์žˆ๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ

BDD(Behavior Driven Development)

BDD๋ž€? ํ–‰์œ„ ์ฃผ๋„ ๊ฐœ๋ฐœ์ด๋‹ค. ํ–‰์œ„ ์ฃผ๋„ ๊ฐœ๋ฐœ์ด ๋„๋Œ€์ฒด ๋ญ”๊ฐ€..? ํ•œ๊ตญ๋ง์ธ๋ฐ ๋„ˆ๋ฌด ์–ด๋ ต๋‹ค. ๊ธฐ๋ณธ ๊ฐœ๋…์„ ์ดํ•ดํ•˜๋Š”๋ฐ ๋„์›€์ด ๋œ ์˜์ƒ TDD, BDD?

๊ธฐํš๋‹จ๊ณ„์—์„œ ๋งŒ๋“ค์–ด์ง„ ์‚ฌ์šฉ์ž ๊ฒฝํ—˜์„ ์ฝ”๋“œ๋กœ ์˜ฎ๊ฒจ์„œ ํ…Œ์ŠคํŠธ ํ•˜๋Š” ๊ณผ์ •์„ BDD๋ผ๊ณ  ํ•œ๋‹ค.

  • Given(์ฃผ์–ด์ง„ ํ™˜๊ฒฝ - ์‚ฌ์šฉ์ž๊ฐ€ ๋กœ๊ทธ์ธ์„ ํ•˜๋ ค๊ณ  ํ• ๋•Œ)

  • When(ํ–‰์œ„ - ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜๋Š” Input์ฐฝ์— ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜๋ฉด)

  • Then(๊ฒฐ๊ณผ - ์ž…๋ ฅํ•œ ์ด๋ฆ„์ด ํ™”๋ฉด์— ๋ณด์—ฌ์ง„๋‹ค)

BDD๋Š” TDD์—์„œ ํŒŒ์ƒ๋œ ๊ฐœ๋…์œผ๋กœ BDD ํ…Œ์ŠคํŠธ๋กœ ์œ ์ € ์‹œ๋‚˜๋ฆฌ์˜ค๋ฅผ ๊ฒ€์ฆํ•˜๊ณ , ์‹œ๋‚˜๋ฆฌ์—์„œ ์‚ฌ์šฉ๋œ ๋ชจ๋“ˆ์€ TDD๋กœ ์ž‘์„ฑ๋œ๋‹ค. BDD ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋กœ ์‹œ๋‚˜๋ฆฌ์˜ค ๊ฒ€์ฆ์„ ํ•˜๋‹ค๋ณด๋ฉด ๊ธฐํš๋‹จ๊ณ„์—์„œ ๋ˆ„๋ฝ๋œ ๋ถ€๋ถ„๋„ ์ฐพ์„ ์ˆ˜ ์žˆ๋‹ค.

Test Code ์ž‘์„ฑํ•ด๋ณด๊ธฐ

๋ฒ”์šฉ์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” Text์ž…๋ ฅ filed๋ฅผ ๋งŒ๋“œ๋Š” ์—ฐ์Šต

import {render, screen} from '@testing-library/react'
import TextField from './Textfield'

test('TextField', ()=> {

    //given
    const label = 'Name'
    const text = 'Tester'
    const setText = () => {}

    //when
    <TextField
        label={label}
        placeholder=''
        text={text}
        setText={setText}
    />

    //then
    screen.getByLabelText('Name')
    
})

given ๋‹จ๊ณ„์—์„œ ํ•„์š”ํ•œ ๊ฐ’์„ ์ค€๋น„ํ•ด์ฃผ๊ณ , ํ•ด๋‹น ๊ฐ’์„ TextField์— ๋„ฃ์—ˆ์„ ๋•Œ ๊ธฐ๋Œ€ํ•˜๋Š” ํ™”๋ฉด์„ ํ…Œ์ŠคํŠธํ•œ๋‹ค.

์ข€ ๋” ๋‹ค์–‘ํ•œ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค ์ถ”๊ฐ€ํ•˜๊ธฐ

import { render, screen, fireEvent } from '@testing-library/react'

import TextField from './TextField'

const context = describe

describe("TextField", () => {

    const label = 'Name'
    const text = 'Tester'
    const setText = jest.fn()

    // ์ดˆ๊ธฐํ™” ํ•ด์ฃผ๊ธฐ
    beforeEach(() => {
        setText.mockClear()
    })
    // when
    // ์ค‘๋ณต๋˜๋Š” ํ•จ์ˆ˜ ๊บผ๋‚ด๊ธฐ
    function renderTextField() {
        render((
            <TextField
                label={label}
                text={text}
                setText={setText}
            />
        ))
    }

    //then
    if('render an input control', () => {
        renderTextfield()

        screen.getByLabelText('Name')
    })

    context('when user types text', () => {
        if('calls the change handler', () => {
            renderTextField()
            //when
            fireEvent.change(screen.getByLabelText(label), {
                target: {
                    value: 'New Name',
                }
            })
            //then
            expect(setText).toBeCalledWith('New Name')
        })
    })
})

ํ…Œ์ŠคํŠธ ์ฝ”๋“œ๋ฅผ ๋งŒ๋“œ๋Š”๊ฑด ์ •๋ง ์–ด๋ ค์›Œ..!

Last updated