Setup Functions

๐Ÿฆ‰ I want to talk with you about something. You can read more about this in a blog post titled Avoid Nesting when you're Testing which is where these examples came from.
You may have see tests like this in the past (don't look too closely, just here to give you an idea of the shape of these kinds of tests):
import { render } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'

import Login from '../login'

describe('Login', () => {
	let utils,
		handleSubmit,
		user,
		changeUsernameInput,
		changePasswordInput,
		clickSubmit

	beforeEach(async () => {
		handleSubmit = jest.fn()
		user = { username: 'michelle', password: 'smith' }
		utils = await render(<Login onSubmit={handleSubmit} />)
		changeUsernameInput = value =>
			userEvent.type(utils.getByLabelText(/username/i), value)
		changePasswordInput = value =>
			userEvent.type(utils.getByLabelText(/password/i), value)
		clickSubmit = () => userEvent.click(utils.getByText(/submit/i))
	})

	describe('when username and password is provided', () => {
		beforeEach(() => {
			changeUsernameInput(user.username)
			changePasswordInput(user.password)
		})

		describe('when the submit button is clicked', () => {
			beforeEach(() => {
				clickSubmit()
			})

			it('should call onSubmit with the username and password', () => {
				expect(handleSubmit).toHaveBeenCalledTimes(1)
				expect(handleSubmit).toHaveBeenCalledWith(user)
			})
		})
	})

	describe('when the password is not provided', () => {
		beforeEach(() => {
			changeUsernameInput(user.username)
		})

		describe('when the submit button is clicked', () => {
			let errorMessage
			beforeEach(() => {
				clickSubmit()
				errorMessage = utils.getByRole('alert')
			})

			it('should show an error message', () => {
				expect(errorMessage).toHaveTextContent(/password is required/i)
			})
		})
	})

	describe('when the username is not provided', () => {
		beforeEach(() => {
			changePasswordInput(user.password)
		})

		describe('when the submit button is clicked', () => {
			let errorMessage
			beforeEach(() => {
				clickSubmit()
				errorMessage = utils.getByRole('alert')
			})

			it('should show an error message', () => {
				expect(errorMessage).toHaveTextContent(/username is required/i)
			})
		})
	})
})
Personally, I find this kind of test extremely hard to work with. The number of nested blocks and shared variables makes it hard to follow the flow of the test and understand what's going on.
The point is there's some shared setup that needs to happen for each test. But using test hooks and function scope for variables to do so is very confusing. We can do better:
import { render } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'

import Login from '../login'

// here we have a bunch of setup functions that compose together for our test cases
// I only recommend doing this when you have a lot of tests that do the same thing.
// I'm including it here only as an example. These tests don't necessitate this
// much abstraction. Read more: https://kcd.im/aha-testing
async function setup() {
	const handleSubmit = jest.fn()
	const utils = await render(<Login onSubmit={handleSubmit} />)
	const user = { username: 'michelle', password: 'smith' }
	const changeUsernameInput = value =>
		userEvent.type(utils.getByLabelText(/username/i), value)
	const changePasswordInput = value =>
		userEvent.type(utils.getByLabelText(/password/i), value)
	const clickSubmit = () => userEvent.click(utils.getByText(/submit/i))
	return {
		...utils,
		handleSubmit,
		user,
		changeUsernameInput,
		changePasswordInput,
		clickSubmit,
	}
}

async function setupSuccessCase() {
	const utils = await setup()
	utils.changeUsernameInput(utils.user.username)
	utils.changePasswordInput(utils.user.password)
	utils.clickSubmit()
	return utils
}

async function setupWithNoPassword() {
	const utils = await setup()
	utils.changeUsernameInput(utils.user.username)
	utils.clickSubmit()
	const errorMessage = utils.getByRole('alert')
	return { ...utils, errorMessage }
}

async function setupWithNoUsername() {
	const utils = await setup()
	utils.changePasswordInput(utils.user.password)
	utils.clickSubmit()
	const errorMessage = utils.getByRole('alert')
	return { ...utils, errorMessage }
}

test('calls onSubmit with the username and password', async () => {
	const { handleSubmit, user } = await setupSuccessCase()
	expect(handleSubmit).toHaveBeenCalledTimes(1)
	expect(handleSubmit).toHaveBeenCalledWith(user)
})

test('shows an error message when submit is clicked and no username is provided', async () => {
	const { handleSubmit, errorMessage } = await setupWithNoUsername()
	expect(errorMessage).toHaveTextContent(/username is required/i)
	expect(handleSubmit).not.toHaveBeenCalled()
})

test('shows an error message when password is not provided', async () => {
	const { handleSubmit, errorMessage } = await setupWithNoPassword()
	expect(errorMessage).toHaveTextContent(/password is required/i)
	expect(handleSubmit).not.toHaveBeenCalled()
})
To me, this is much easier to understand. It may be a little overkill for the purpose of the example, but the point is if you have shared setup you can use regular JavaScript mechanisms (functions!) rather than complicated wiring together of hooks.
I call these functions simply "setup functions". But they're similar to the idea of "Object Mother" or a "Test Object Factory". You can read even more about these ideas in my blog post titled AHA Testing.
๐Ÿ‘จโ€๐Ÿ’ผ Great, with that context, could you make a setup function for creating our request object please?
Don't overthink this one. We're literally just moving some code into a function, but it's important enough that we want to make you do it anyway.
Login to get access to the exclusive discord channel.
  • general
    npm install everytime I setup a new playground
    Duki ๐ŸŒŒ:
    Is it normal that I have to run `npm install` in my playground directory, everytime I setup the play...
    • โœ…1
    2 ยท 14 days ago
  • general
    Welcome to EpicWeb.dev! Say Hello ๐Ÿ‘‹
    Kent C. Dodds โ—† ๐Ÿš€๐Ÿ†๐ŸŒŒ:
    This is the first post of many hopefully!
    • 18
    80 ยท 6 days ago
  • general
    Migration to Vite: Server-only module referenced by client
    Fabian ๐ŸŒŒ:
    Hi, I'm working on migrating to Vite following the remix docs (https://remix.run/docs/en/main/guides...
    • โœ…1
    1 ยท 3 months ago
  • general
    Remix Vite Plugin
    Binalfew ๐Ÿš€ ๐ŸŒŒ:
    <@105755735731781632> Now that remix officially supports vite (though not stable) what does it mean...
    • โœ…1
    3 ยท a year ago
  • general
    ๐Ÿ”ญfoundations
    Solutions video on localhost:5639 ?
    quang ๐Ÿš€ ๐ŸŒŒ:
    Hi, so I'm having a hard time navigating (hopefully will be better with time) The nav on epicweb.de...
    • โœ…1
    9 ยท a year ago
  • ๐Ÿงชfull stack testing
    Failing tests in full-stack-testing workshop
    Szabolcs ๐ŸŒŒ:
    I am getting this warning in the testing workshop. ``` Warning: `ReactDOMTestUtils.act` is deprecate...
    • โœ…1
    2 ยท 4 months ago
  • general
    Epicshop is now social and mobile friendly!
    Kent C. Dodds โ—† ๐Ÿš€๐Ÿ†๐ŸŒŒ:
    I'm excited to announce that now the Epic Web workshops are mobile friendly! https://foundations.ep...
    • ๐ŸŽ‰2
    0 ยท 5 months ago
  • ๐Ÿ’พdata
    general
    ๐Ÿ“forms
    ๐Ÿ”ญfoundations
    double underscore?
    trendaaang ๐ŸŒŒ:
    What with the `__note-editor.tsx`? I don't see that in the Remix docs and I don't remember Kent talk...
    • โœ…1
    2 ยท 6 months ago
  • ๐Ÿ”ญfoundations
    ๐Ÿ’พdata
    general
    ๐Ÿ“forms
    ๐Ÿ”auth
    Native Logging
    trendaaang ๐ŸŒŒ:
    I was thinking that it could be useful to log every CRUD operation to help track down errors. Is tha...
    • โœ…1
    6 ยท 7 months ago
  • general
    The video play is pretty laggy currently
    QzCurious ๐ŸŒŒ:
    I thought I should tag you for this <@105755735731781632>. Please take a look if something wrong.
    • โœ…2
    9 ยท 8 months ago
  • general
    New Workshop Scheduled
    Kent C. Dodds โ—† ๐Ÿš€๐Ÿ†๐ŸŒŒ:
    Hey Epic Web devs! I wanted to let you know before everyone else on here: https://www.epicweb.dev/ev...
    • 2
    0 ยท 8 months ago