net - UK (2020-01)

(Antfer) #1

PROJECTS
React


WHAT IS TEST-DRIVEN


DEVELOPMENT?


IN-DEPTH

TDD, or test-driven development, is a testing discipline that
forces you to think about edge cases when you’re in the
process of development.
You start out with a hypothesis that forms the basis for your
tests. This could be something like ‘it renders a button’ or ‘it
renders a button using the dark mode UI on click’, then you go
ahead and write your tests.
Only after you have at least three robust tests that you can use
to verify what your component’s behaviour will be, should you
start coding the actual component.
I like this concept because it forces you to think about the
structure of your component from completely different angles.
You’re not trying to preserve the code you already wrote, so you
can find different ideas more easily.
Be careful though: you can write tests that will pass under any
circumstances! For this reason, three or more tests are often
required to enable you to ‘triangulate’ or effectively define the
functionality of your component before you can start building it.

Above If you prefer courses to help you get started, it’s worth checking out the one by
Kent C Dodds (who wrote and maintains React Testing Library)

const modeToggle = () => {
const [mode, setMode] = useState[‘light’]
const toggleTheme = () => {
if (theme === ‘light’) {
setTheme(‘dark’)
} else {
setTheme(‘light’)
}
}
return (
<ToggleButton data-testid=”mode-toggle”
lightMode={mode} onClick={toggleMode}>
Toggle mode
</ToggleButton>
)
}

First, we should add a test id onto the button so that we
can find it in the render phase:

return (
<ToggleButton
data-testid=”mode-toggle”
lightMode={mode}
onClick={toggleMode}
>
Toggle mode
</ToggleButton>
)

Did you notice that we added the new attribute
data-testid to the button? Here’s how you might test
that. First, import a new function, fireEvent from the
testing library:

import { cleanup,
fireEvent,
render
} from ‘@testing-library/react’

We can use that function to test there are changes in
the UI and that those changes are consistent:

it(‘renders with basic props’, () => {
const { container } = render(<ToggleButton />
)
expect(container).toMatchSnapshot()
})
it(‘renders the light UI on click’, () => {
const { container, getByTestId } = render(<ToggleButton
/>)
fireEvent.click(getByTestId(‘mode-toggle’))
expect(container).toMatchSnapshot()
})
Free download pdf