Skip to content

feat: swap / useFake#3

Merged
thetutlage merged 2 commits into5.xfrom
feat/swap
Mar 23, 2026
Merged

feat: swap / useFake#3
thetutlage merged 2 commits into5.xfrom
feat/swap

Conversation

@Julien-R44
Copy link
Copy Markdown
Member

@Julien-R44 Julien-R44 commented Mar 20, 2026

Quick QOL helper. Adds a swap method on japa's TestContext that lets you replace a container binding with a fake for the duration of a test. binding gets auto-restored after the test completes via cleanup.

// via test ctx
test('sends welcome email', async ({ swap }) => {
  const fakeMailer = new FakeMailer()
  swap(Mailer, fakeMailer)

  await userService.register({ email: 'joe@example.com' })
  fakeMailer.assertSent('joe@example.com')
})

// via useFake
import { useFake } from '@japa/plugin-adonisjs/helpers'

test('sends welcome email', async () => {
  useFake(Mailer, new FakeMailer())

  await userService.register({ email: 'joe@example.com' })
  fakeMailer.assertSent('joe@example.com')
})

So i've been copy/pasting a little useFake helper across all my projects for a while now

it's pretty elegant compared to manually doing container.swap + container.restore in every single test, you just call it and forget about cleanup. felt like it deserved to live in the core properly instead of being a personal snippet

@Julien-R44 Julien-R44 changed the title feat: swap feat: swap / useFake Mar 20, 2026
@thetutlage thetutlage merged commit 8b52dfb into 5.x Mar 23, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants