Last active
January 28, 2019 18:04
-
-
Save kentcdodds/7a9bed9639cb8900d0bce9f0c513c8c9 to your computer and use it in GitHub Desktop.
Example of a test that doesn't use enzyme or TestUtils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For this tweet: https://twitter.com/kentcdodds/status/974107759233740800