Skip to content

Commit

Permalink
Adds integration tests for bypass/fall-through response patching beha…
Browse files Browse the repository at this point in the history
…viors
  • Loading branch information
kettanaito committed Jul 16, 2020
1 parent 041061d commit 9b7656d
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 37 deletions.
37 changes: 0 additions & 37 deletions test/msw-api/setup-server/response-patching.test.ts

This file was deleted.

83 changes: 83 additions & 0 deletions test/msw-api/setup-server/scenarios/response-patching.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/**
* @jest-environment node
*/
import fetch from 'node-fetch'
import { rest } from 'msw'
import { setupServer } from 'msw/node'

const server = setupServer(
rest.get('https://test.mswjs.io/user', async (req, res, ctx) => {
const originalResponse = await ctx.fetch('https://httpbin.org/get')

return res(
ctx.json({
url: originalResponse.url,
mocked: true,
}),
)
}),
rest.get('https://test.mswjs.io/complex-request', async (req, res, ctx) => {
const bypass = req.url.searchParams.get('bypass')
const shouldBypass = bypass === 'true'
const performRequest = shouldBypass
? () => ctx.fetch('https://httpbin.org/post', { method: 'POST' })
: () =>
fetch('https://httpbin.org/post', { method: 'POST' }).then((res) =>
res.json(),
)
const originalResponse = await performRequest()

return res(
ctx.json({
url: originalResponse.url,
mocked: true,
}),
)
}),
rest.post('https://httpbin.org/post', (req, res, ctx) => {
return res(ctx.json({ url: 'completely-mocked' }))
}),
)

beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())

test('returns a combination of mocked and original responses', async () => {
const res = await fetch('https://test.mswjs.io/user')
const { status, headers } = res
const body = await res.json()

expect(status).toBe(200)
expect(headers.get('x-powered-by')).toBe('msw')
expect(body).toEqual({
url: 'https://httpbin.org/get',
mocked: true,
})
})

test('bypasses a mocked request when using "ctx.fetch"', async () => {
const res = await fetch('https://test.mswjs.io/complex-request?bypass=true')
const { status, headers } = res
const body = await res.json()

expect(status).toBe(200)
expect(headers.get('x-powered-by')).toBe('msw')
expect(body).toEqual({
url: 'https://httpbin.org/post',
mocked: true,
})
})

test('falls into the mocked request when using "fetch" directly', async () => {
const res = await fetch('https://test.mswjs.io/complex-request')
const { status, headers } = res
const body = await res.json()

expect(status).toBe(200)
expect(headers.get('x-powered-by')).toBe('msw')
expect(body).toEqual({
url: 'completely-mocked',
mocked: true,
})
})

0 comments on commit 9b7656d

Please sign in to comment.