Seamless REST/GraphQL API mocking library for browser and Node.js.
MIT License
Bot releases are hidden (Show)
graphql.link
request handler that allows to mock GraphQL operations on per-endpoint basis (#315, #319).import { setupWorker, graphql } from 'msw'
const github = graphql.link('https://api.github.com/graphql')
const stripe = graphql.link('https://api.stripe.com/graphql')
const worker = setupWorker(
github.query('GetUser', resolver),
stripe.mutation('Payment', resolver),
)
worker.start()
ERROR in node_modules/msw/lib/types/context/cookie.d.ts:1:8 - error TS1192:
Module '"/node_modules/@types/cookie/index"' has no default export.
composeMocks
function has been removed (#236, #239). Please use setupWorker
instead.-import { composeMocks, rest } from 'msw'
-composeMocks(rest.get(...))
+import { setupWorker, rest } from 'msw'
+setupWorker(rest.get(...))
import { setupServer } from 'msw/native'
import { rest } from 'msw'
const server = setupServer(
rest.get('/user', (req, res, ctx) => {
return res(ctx.json({ firstName: 'John' })
})
)
The
setupServer
API for React Native is the exact mirror of the same API for NodeJS. Read more in the documentation: https://mswjs.io/docs/api/setup-server
setupWorker
docs, setupServer
docs).const server = setupServer(
rest.get('/books', (req, res, ctx) => res())
)
server.listen({
onUnhandledRequest: 'error'
})
fetch('/user') // ERROR! Unhandled request.
req.cookies
property to access a request’s cookies (#199, #261, Accessing request cookies recipe).res.networkError
API):rest.post('/login', (req, res, ctx) => {
return res.networkError('Custom error message')
})
worker.start()
or Hot Reload (#244).XMLHttpRequest.prototype.addEventListener
events being ignored (#267).req.body
in case of GraphQL request (#297, #302).setupWorker
in a NodeJS environment (#219).setupServer
in a browser environment (#214, #219).worker.start()
and the worker script doesn’t exist (#237, #242).GraphQLMockedRequest
, GraphQLMockedContext
, GraphQLRequestPayload
, GraphQLResponseResolver
types (#213, #241).ctx.delay()
to 5ms when run in Node environment (including jsdom) (#205).jest.useFakeTimers()
in your tests (#243).ctx.delay()
without any arguments now simulates a random realistic server response time in a range between 100-400ms (#192, #198). Responses in Node are instantaneous.Uncaught (in promise) SyntaxError: Unexpected end of input
exception when processing a request. Internally, a request’s body is now always retrieved as text, parsing it as JSON is delegated to the client side (based on the Content-Type
header) (#200, #201).worker.start()
and successful worker activation. This eliminates race condition between the two, and now comes as the default behavior. (#190, #196)The behavior of deferring requests can be configured using the waitUntilReady: boolean
option on worker.start()
:
import { setupWorker, rest } from 'msw'
const worker = setupWorker(/* request handlers */)
worker.start({
// You can opt-out of the deferred network requests behavior.
waitUntilReady: false
})
.use()
to prepend any request handlers. Any prepended request handlers take priority over existing ones, if their predicate match.
.restoreHandlers()
to mark any used one-time request handlers as unused, allowing them to affect network again.
.resetHandlers()
to remove any request handlers added on runtime. Optionally accepts a list of next request handlers that replace the initial handlers passed to setupServer
/setupWorker
call.
res.once()
. Such handles will respond with a given mocked response only once upon request match:rest.get('/books', (req, res, ctx) => {
return res.once(ctx.json([1, 2, 3]))
})
msw
(#185, #186 ):TS7016: Could not find a declaration file for module 'cookie'
mockServiceWorker.js
file.parse()
, to retrieve additional information about the request before the predicate.getPublicRequest()
, to modify the original request with public information (i.e. adding req.params
or req.variables
).log
function that controls what and how gets printed into browser’s console for introspection:// my-handler.js
export const myHandler = () => {
return {
log(req, res, handler) {
console.log('%s %s', req.method, req.url.href)
}
}
}
The information available in the log
function:
req
, intercepted request instance;res
, resolved mocked response object;handler
, exact request handler that captured this request.Content-Type: application/json
to be unparsed in req.body
reference of the request handler (#171, #172).This release introduces bug fixes to the Service Worker file. Please follow the update instructions in your browser's console. Thanks.
req.url
reference in request handlers is now a URL
instance (#158):rest.get('/user', (req) => {
- req.url // "/user"
+ req.url.href // "/user"
})
// test/LoginForm.test.js
import { rest } from 'msw'
import { setupServer } from 'msw/node'
describe('LoginForm', () => {
const server = setupServer(
rest.post('/login', (req, res, ctx) => {
return res(ctx.json({ success: true }))
})
)
beforeAll(() => {
server.listen()
})
afterAll(() => {
server.close()
})
it('allows a user to log in', () => {
// your assertions here...
})
})
req.headers
(#154)This release contains changes to
mockServiceWorker.js
file. Please follow the instructions in your browser's console to update the worker file.
ctx.fetch()
(#150, #151):Failed to execute 'text' on 'Response': body stream is locked
mockServiceWorker.js
file relatively to the path, instead of the root (#152, #153).ctx.fetch()
to perform response patching (#145, #149).