Skip to content

Save ids with hooks

hooks.ts: ctx is the store of the user who made the request, so ids never leak between users.

h.posts.create.after(({ response, ctx }) => {
if (response.status === 201) {
ctx.set({ key: 'lastPostId', value: response.body.id })
}
})

posts.test.ts:

const created = await alice.posts.create({ body: { title: 'Hello', content: 'First post' } })
created.assert(201, { title: 'Hello', publishedAt: null })
const postId = alice.get({ key: 'lastPostId' })
expect(postId).toBe(created.assert(201).body.id)
expect(bob.getSafe({ key: 'lastPostId' })).toBeUndefined()

get throws if the value is not set (say, the request failed and the hook skipped it), so the test fails right there with a clear message. Where a value may legitimately be missing, use getSafe: it returns undefined instead.

Privacy-friendly analytics, no cookies.