Skip to content

Commit

Permalink
test: add one-time handler tests
Browse files Browse the repository at this point in the history
  • Loading branch information
kettanaito committed Oct 21, 2023
1 parent 7d6d82d commit b2baefc
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/core/handlers/HttpHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,3 +216,45 @@ describe('run', () => {
expect(await run()).toBe('complete')
})
})

describe('once', () => {
it('marks a matching one-time handler as used', async () => {
const handler = new HttpHandler(
'GET',
'/resource',
() => {
return HttpResponse.text('Mocked')
},
{
once: true,
},
)

const request = new Request(new URL('/resource', location.href))
const result = await handler.run({
request,
})

expect(handler.isUsed).toBe(true)
expect(result?.handler).toEqual(handler)
expect(await result?.response?.text()).toBe('Mocked')

const resultAfterUsed = await handler.run({
request,
})
expect(handler.isUsed).toBe(true)
expect(resultAfterUsed?.handler).toBeUndefined()
})

it('does not mark a non-matching one-time-handler as used', async () => {
const handler = new HttpHandler('GET', '/resource', () => undefined, {
once: true,
})

const result = await handler.run({
request: new Request(new URL('/non-matching', location.href)),
})

expect(result?.handler).toBeUndefined()
})
})
44 changes: 44 additions & 0 deletions src/core/utils/handleRequest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,3 +342,47 @@ it('returns undefined without warning on a passthrough request', async () => {
expect(callbacks.onPassthroughResponse).toHaveBeenNthCalledWith(1, request)
expect(callbacks.onMockedResponse).not.toHaveBeenCalled()
})

it('marks the first matching one-time handler as used', async () => {
const { emitter } = setup()

const oneTimeHandler = http.get(
'/resource',
() => {
return HttpResponse.text('One-time')
},
{ once: true },
)
const anotherHandler = http.get('/resource', () => {
return HttpResponse.text('Another')
})
const handlers: Array<RequestHandler> = [oneTimeHandler, anotherHandler]

const requestId = uuidv4()
const request = new Request('http://localhost/resource')
const firstResult = await handleRequest(
request,
requestId,
handlers,
options,
emitter,
callbacks,
)

expect(await firstResult?.text()).toBe('One-time')
expect(oneTimeHandler.isUsed).toBe(true)
expect(anotherHandler.isUsed).toBe(false)

const secondResult = await handleRequest(
request,
requestId,
handlers,
options,
emitter,
callbacks,
)

expect(await secondResult?.text()).toBe('Another')
expect(anotherHandler.isUsed).toBe(true)
expect(oneTimeHandler.isUsed).toBe(true)
})

0 comments on commit b2baefc

Please sign in to comment.