Seamless REST/GraphQL API mocking library for browser and Node.js.
MIT License
Bot releases are hidden (Show)
worker.start()
will now reject in the case of any errors during the worker registration (#607).RestRequestType
, use RestRequest
instead.GraphQLMockedRequest
, use GraphQLRequest
instead.GraphQLMockedContext
, use GraphQLContext
instead.GraphQLRequestPayload
, use GraphQLRequestBody
instead.GraphQLRequestParsedResult
, use ParsedGraphQLRequest
instead.GraphQLResponseResolver
MockedRequest
type no longer have the params
key (#561). Please use the RestRequest
type to annotate REST API requests instead.msw.workerDirectory
property in your package.json:{
"msw": {
"workerDirectory": "public"
}
}
Starting from this release, whenever you install msw
, it will try to locate the msw.workerDirectory
property in your package.json and copy the relevant worker script (mockServiceWorker.js
) to that directory.
Whenever running msw init
now, you will be prompted to save your public directory choice to package.json.
msw init
you can pass the —save
option to automatically save the public directory in your package.json for future worker updates (#606). You can alternatively use --no-save
to bail out this step.response:*
life-cycle events (#570).res.once
) affected multiple matching requests made in parallel (#583).OnUnhandledRequest
type as the new UnhandledRequestStrategy
type (#577).onUnhandledRequest
option will now suggest similar request handlers based on the URL/operation name similarity (#560).Response
instance for the response:*
life-cycle event (#570).onUnhandledRequest: "error"
option resulted in a thrown exception being gracefully handled by Axios (#544). The "error"
value now prints to stderr
directly instead of throwing an exception. An original request-related exception will become visible now as well.This release introduces changes to the
mockServiceWorker.js
file. Please follow the instructions in the browser to update the worker file. Thank you.
ctx.delay() // random realistic response time
ctx.delay('real') // the same as `ctx.delay()`
ctx.delay('infinite') // infinite response time
ctx.delay(50) // explicit response delay (50ms)
[MSW] Mocking disabled
message when calling worker.stop()
. (#485, #493).Failed to construct 'Response': The status provided (0) is outside the range [200, 599].
exception caused by an opaque response on the page (#529, #564). MSW will now skip opaque responses during the life-cycle events handling. You will not get the response:bypass
invoked upon an opaque response.
ExecutionResult
of graphql
was not compatible with ctx.data
and ctx.errors
utilities (#522, #542).self
instead of this
in the worker script (#568).ctx.json
context utility now always stringifies the response body (#468).import { ResponseTransformer, compose } from 'msw'
import base64Image from 'url-loader!../../fixtures/image.jpg'
async function jpeg(base64: string): Promise<ResponseTransformer> {
const buffer = await fetch(base64).then((res) => res.arrayBuffer())
return compose(
context.set('Content-Length', buffer.byteLength.toString()),
context.set('Content-Type', 'image/jpeg'),
context.body(buffer),
)
}
const worker = setupWorker(
rest.get('/image', async (req, res, ctx) => {
return res(await jpeg(base64Image))
}),
})
compose
function (#467).import { compose } from 'msw'
.printHandlers()
method (#310, #450).
node-match-path
0.6.0.ctx.data
and ctx.errors
in GraphQL responses (#401, #403).graphql.query('GetUser', (req, res, ctx) => {
return res(
ctx.data({ id: 'abc-123' }),
ctx.errors([
{ message: 'Failed to get user posts' }
])
)
})
rest.get<RequestType, ResponseType, RequestParamsType>(url, resolver)
setupWorker
/setupServer
functions to be a spread list of handlers, not an Array (#400, #402).graphql
handler by exporting the GraphQLRequestParsedResult
type from the package (#425).This release contains changes to the
mockServiceWorker.js
file. Please follow the instructions in your browser to upgrade the Service Worker file.
ctx.fetch
utility now returns the entire response, not just the body (#373).- const body = await ctx.fetch(req)
+ const response = await ctx.fetch(req)
+ const body = await response.json()
graphql.operation
API (#343).import { graphql } from 'msw'
graphql.operation((req, res, ctx) => {
const { query, variables } = req.body
// Execute any GraphQL operation against a mock schema
// and return the response.
return executeSchema(mockSchema, { query, variables })
})
rest.*
request handlers (#345, #352).import { rest } from 'msw'
interface UserResponseBodyType {
firstName: string
}
rest.get<never, UserResponseBodyType>('/user', (req, res, ctx) => {
return res(ctx.json({ firstName: ‘John’ })
})
interface TodoRequestBodyType {
title: string
}
type TodoResponseBodyType = string[]
rest.post<TodoRequestBodyType, TodoResponseBodyType>('/todo', (req, res, ctx) => {
const { title } = req.body
return res(ctx.json(['one', title]))
})
rest.head()
request handler to match HEAD
method requests (#356).findWorker
option to worker.start()
to locate the mock Service Worker script at a custom location (#335, #351).ctx.json
now supports any data types that can be serialized to a valid JSON (#349, #350).worker.start()
not being deeply merged with the default ones (#347, #348).ctx.json()
utility function accepting only objects. Now it accepts any data that can be stringified into JSON (#349, #350).setupServer
(https://github.com/mswjs/node-request-interceptor/issues/49, https://github.com/mswjs/node-request-interceptor/pull/50).Export has or is using name 'ParsedRestRequest' from external module
error message when compiling a TypeScript project using MSW (#325, #333).node-request-interceptor
to version 0.3.5
(see Changelog).query
property (#234, #328, #329).http
module being patched in React Native environment, where it's not present (#203, #331).[email protected]
(#331)