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
    Epic stack using tanstack form
    wargha ๐Ÿš€ ๐ŸŒŒ:
    https://github.com/epicweb-dev/epic-stack/compare/epicweb-dev:main...wargha:feature/tanstack-form-ex...
    • โœ…1
    2 ยท 2 hours ago
  • general
    Init command outdated on the EpicWeb website
    Virgile ๐Ÿ† ๐ŸŒŒ:
    Hi everyone. I've initialized a new epic-stack project yesterday. Following instructions from http...
    • โœ…1
    3 ยท 3 days ago
  • general
    Mark as complete, resets the first time you click it.
    Daniel V.C ๐Ÿš€ ๐ŸŒŒ:
    Not sure if anyone else has had this issue, as i've not seen anyone else talk about it, but I find ...
    • โœ…1
    8 ยท 9 days ago
  • general
    Keeping Epic Stack Projects Free on Fly โ€“ Any Tips?
    wargha ๐Ÿš€ ๐ŸŒŒ:
    Iโ€™ve been experimenting with the Epic Stack and deploying some dummy projects on Fly. I noticed that...
    • โœ…1
    0 ยท 21 days ago
  • general
    epic stack website initial load at home page is unstyled (sometimes)
    osmancakir ๐Ÿš€ ๐ŸŒŒ:
    Sometimes (especially when it is loaded first time on a new browser etc.) I see this unstyled versio...
    10 ยท 7 days 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 ยท a year ago
  • general
    Welcome to EpicWeb.dev! Say Hello ๐Ÿ‘‹
    Kent C. Dodds โ—† ๐Ÿš€๐Ÿ†๐ŸŒŒ:
    This is the first post of many hopefully!
    • 18
    81 ยท 2 years ago
  • ๐Ÿ’พdata
    general
    ๐Ÿ“forms
    ๐Ÿ”ญfoundations
    Creating Notes
    Scott ๐ŸŒŒ ๐Ÿ†:
    Does anybody know in what workshop we create notes? I would like to see the routing structure. So fa...
    • โœ…1
    2 ยท 3 months ago
  • ๐Ÿ”ญfoundations
    ๐Ÿ’พdata
    general
    ๐Ÿ“forms
    ๐Ÿ”auth
    Thank you for the inspiration
    Binalfew ๐Ÿš€ ๐ŸŒŒ:
    <@105755735731781632> I wanted to thank you for the incredible knowledge I gained from your Epic Web...
    • โค๏ธ1
    1 ยท 3 months ago
  • 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 ยท 5 months 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 ยท 8 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 ยท 9 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 ยท 10 months ago