Adrianna Valdivia
@adriannavaldivi
MOTHER
UI ENGINEER @ SALESLOFT
PREVIOUSLY WORKED AT POLAR NOTION AND MAILCHIMP
WOMEN WHO CODE ATL EVANGELIST
#1 Best Place to Work in Atlanta
2018 and 2019
base library | top level library |
---|---|
queries | render |
firing events | cleanup |
async utilities | act |
helpers |
DTL | RTL |
---|
import { render } from '@testing-library/react'
const { getByLabelText } = render(<Login />)
const node = getByLabelText('username')
ByLabelText | ByPlaceholderText | ByAltText |
---|---|---|
ByTitle | ByRole | |
ByTestId | ByDisplayValue | ByText |
Basic usage:
npm install --save-dev @testing-library/react
Steps to testing your component
....
export const BasicComponent = ({ title }) => {
return(
<h1>{title}</h1>
)
}
import React from 'react'
import { fireEvent, render } from '@testing-library/react'
import { BasicComponent } from './BasicComponent'
const getProps = (title = "React Testing Library") => {
return {
title
}
}
describe('Basic Component', () => {
afterEach(cleanup)
it('displays the default title text', () => {
const props = getProps()
const { getByText } = render(
<BasicComponent {...props} />
)
const title = getByText(props.title)
expect(title).toBeDefined()
expect(title).toEqual("React Testing Library")
})
})
BasicComponent.js
BasicComponent.spec.js
import React from 'react'
import p from 'prop-types'
import { ButtonContainer } from './Button.styles'
export const Button = ({ text, width, disabled, onClick }) => {
return (
<ButtonContainer
data-testid="text-input-container"
disabled={disabled}
width={width}
onClick={onClick}
>
{text}
</ButtonContainer>
)
}
)
Button.propTypes = {
disabled: p.boolean,
onClick: p.func,
text: p.string.isRequired,
width: p.oneOfType([p.string, p.number]),
}
Button.defaultProps = {
width: 240,
}
import React from 'react'
import { fireEvent, render } from '@testing-library/react'
import { Button } from './Button'
const getProps = ({
text = "Welcome",
width = "250px"
disabled = false,
onClick = jest.fn()
}) => {
return {
text,
width,
disabled,
onClick,
}
}
describe('Button', () => {
afterEach(cleanup)
it('renders default props', () => {
const props = getProps()
const { getByText } = render(
<Button {...props} />
)
const title = getByText(props.text)
expect(title).toBeDefined()
expect(title).toEqual("React Testing Library")
})
it('calls onClick if disabled is false', () => {
const props = getProps()
const { getByTestId } = render(
<Button {...props} />
)
const button = getByTestId("text-input-container")
fireEvent.click(button)
expect(props.OnClick).toHaveBeenCalledTimes(1)
})
it('does not call onClick if disabled is false', () => {
// what test would you write here to get to pass
})
})