Skip to content

Instantly share code, notes, and snippets.

@lox
Created September 10, 2023 04:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lox/fd71816d14ffa421ab9116b1a72c6d47 to your computer and use it in GitHub Desktop.
Save lox/fd71816d14ffa421ab9116b1a72c6d47 to your computer and use it in GitHub Desktop.
Example of using mswjs interceptors
import { BatchInterceptor } from '@mswjs/interceptors'
import { ClientRequestInterceptor } from '@mswjs/interceptors/ClientRequest'
import { FetchInterceptor } from '@mswjs/interceptors/fetch'
import http from 'http'
const interceptor = new BatchInterceptor({
name: 'my-interceptor',
interceptors: [new ClientRequestInterceptor(), new FetchInterceptor()],
})
// Enable the interception of requests.
interceptor.apply()
// Listen to any "http.ClientRequest" being dispatched,
// and log its method and full URL.
interceptor.on('request', ({ request, requestId }) => {
console.log('⚡️' + request.method, request.url)
})
interceptor.on('request', ({ request, requestId }) => {
request.respondWith(
new Response(
JSON.stringify({
firstName: 'John',
lastName: 'Maverick',
}),
{
status: 201,
statusText: 'Created',
headers: {
'Content-Type': 'application/json',
},
}
)
)
})
// Listen to any responses sent to "http.ClientRequest".
// Note that this listener is read-only and cannot affect responses.
interceptor.on('response', async ({ response, isMockedResponse, request, requestId }) => {
console.log('response to %s %s was:', request.method, request.url, response.status)
const respText = await response.clone().text()
console.log('response', respText)
const reqText = await request.clone().text()
console.log('request', reqText)
})
const server = http.createServer((req, res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ method: req.method, headers: req.headers }))
})
server.listen(3000, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:3000/')
})
const data = JSON.stringify({
todo: 'Buy the milk',
})
const response = await fetch('http://localhost:3000/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: data,
})
const result = await response.json()
console.log('Result:', result)
interceptor.dispose()
server.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment