diff --git a/src/core/handlers/HttpHandler.test.ts b/src/core/handlers/HttpHandler.test.ts index 55f1e0c40..9217e40f8 100644 --- a/src/core/handlers/HttpHandler.test.ts +++ b/src/core/handlers/HttpHandler.test.ts @@ -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() + }) +}) diff --git a/src/core/utils/handleRequest.test.ts b/src/core/utils/handleRequest.test.ts index 2f49662ea..ff0626edd 100644 --- a/src/core/utils/handleRequest.test.ts +++ b/src/core/utils/handleRequest.test.ts @@ -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 = [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) +})