Skip to content

Instantly share code, notes, and snippets.

@kentcdodds
Last active January 28, 2019 18:04
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kentcdodds/7a9bed9639cb8900d0bce9f0c513c8c9 to your computer and use it in GitHub Desktop.
Save kentcdodds/7a9bed9639cb8900d0bce9f0c513c8c9 to your computer and use it in GitHub Desktop.
Example of a test that doesn't use enzyme or TestUtils
import React from 'react'
function Login({onSubmit}) {
return (
<div>
<form
data-test="login-form"
onSubmit={e => {
e.preventDefault()
const {username, password} = e.target.elements
onSubmit({
username: username.value,
password: password.value,
})
}}
>
<input
placeholder="Username..."
name="username"
data-test="username-input"
/>
<input
placeholder="Password..."
type="password"
name="password"
data-test="password-input"
/>
<button type="submit" data-test="login-submit">Submit</button>
</form>
</div>
)
}
export default Login
import React from 'react'
import ReactDOM from 'react-dom'
import Login from './login'
const findElementByTestId = (node, id) =>
node.querySelector(`[data-test="${id}"]`)
test('calls onSubmit with the username and password when submitted', () => {
const fakeUser = {username: 'chucknorris', password: '(╯°□°)╯︵ ┻━┻'}
const handleSubmit = jest.fn()
const div = document.createElement('div')
ReactDOM.render(<Login onSubmit={handleSubmit} />, div)
const usernameNode = findElementByTestId(div, 'username-input')
const passwordNode = findElementByTestId(div, 'password-input')
const formWrapper = findElementByTestId(div, 'login-form')
usernameNode.value = fakeUser.username
passwordNode.value = fakeUser.password
const event = new window.Event('submit')
formWrapper.dispatchEvent(event)
expect(handleSubmit).toHaveBeenCalledTimes(1)
expect(handleSubmit).toHaveBeenCalledWith(fakeUser)
})
@kentcdodds
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment