Mock Service Worker (MSW) - 用于浏览器和node的无缝REST/GraphQL API模拟库
Mock Service Worker (MSW) - 用于浏览器和node的无缝REST/GraphQL API模拟库 kettanaito released this
Improvements
- Ships with refined JSDoc support (#483). Most of the core functions and methods now include concise description, usage example, and a link to the docs.
Assets
2
Features
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))
}),
})
- Publicly exposes the
compose
function (#467).
import { compose } from 'msw'
Assets
2
kettanaito released this
Bug fixes
- Fixes an issue that resulted into
Content-Type: application/json
request body not being parsed as a JSON whenever it had an additionalcharset
header value (#462, #463).
Internals
- Updates package dependencies.
Assets
2
Features
rest.get<RequestType, ResponseType, RequestParamsType>(url, resolver)
- Validates the value given to the
setupWorker
/setupServer
functions to be a spread list of handlers, not an Array (#400, #402).
Bug fixes
- Fixes an issue that caused a TypeScript compilation to fail when importing the
graphql
handler by exporting theGraphQLRequestParsedResult
type from the package (#425).
Assets
2
Bug fixes
Assets
2
Bug fixes
- Fixes an issue that resulted into a
Export has or is using name 'ParsedRestRequest' from external module
error message when compiling a TypeScript project using MSW (#325, #333). - Fixes an issue that resulted into a wrong Service Worker registration being picked up on platforms that register their own workers (i.e. Codesandbox) (#289).
Dependencies
- Updates
node-request-interceptor
to version0.3.5
(see Changelog).
Assets
2
Bug fixes
Assets
2
kettanaito released this
Breaking changes
-import { composeMocks, rest } from 'msw'
-composeMocks(rest.get(...))
+import { setupWorker, rest } from 'msw'
+setupWorker(rest.get(...))
Features
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
- Adds support for binary response types (#221, #224, Binary response type recipe).
- Adds an option to warn/error/execute arbitrary logic on unmatched request (#191,
setupWorker
docs,setupServer
docs).
const server = setupServer(
rest.get('/books', (req, res, ctx) => res())
)
server.listen({
onUnhandledRequest: 'error'
})
fetch('/user') // ERROR! Unhandled request.
- Adds a
req.cookies
property to access a request’s cookies (#199, #261, Accessing request cookies recipe). - Adds support for network error emulation (#253,
res.networkError
API):
rest.post('/login', (req, res, ctx) => {
return res.networkError('Custom error message')
})
Bug fixes
- Fixes an issue that resulted into a "global is not defined" error being thrown in a browser (#255).
- Fixes an issue that resulted into the worker listeners being established multiple times after repetitive calls to
worker.start()
or Hot Reload (#244). - Fixes an issue that failed response patching in NodeJS (#264, #266).
- Fixes an issue that resulted into the
XMLHttpRequest.prototype.addEventListener
events being ignored (#267). - Fixes an issue that resulted into timeout in POST requests with a body in NodeJS (#277).
- Fixes an invalidly typed
req.body
in case of GraphQL request (#297, #302). - Updates library's dependencies (#306).
Assets
2
Features
- Adds a warning when using redundant query parameters in a request handler URL (#231, #233).
- Throws an exception when running
setupWorker
in a NodeJS environment (#219). - Throws an exception when running
setupServer
in a browser environment (#214, #219). - Adds a custom error message when calling
worker.start()
and the worker script doesn’t exist (#237, #242). - Exports GraphQL type annotations for
GraphQLMockedRequest
,GraphQLMockedContext
,GraphQLRequestPayload
,GraphQLResponseResolver
types (#213, #241).
Bug fixes
- Sets the default realistic response time of
ctx.delay()
to 5ms when run in Node environment (including jsdom) (#205). - Fixes an issue that resulted into the response Promise to never resolve when using
jest.useFakeTiners()
in your tests (#243). - Fixes a bug that resulted into a request handler URL with query parameters to produce a false negative match with the identical actual request URL. Query parameters and hashes in a request handler URL no longer affect the matching process.
Assets
2
Bug fixes
Assets
2
kettanaito released this
Features
- The library now defers all the client-side requests that happen between calling
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
})
Assets
2
Features
- Adds support for declaring runtime request handlers (#128, #187):
.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 tosetupServer
/setupWorker
call.
- Adds support for one-time request handlers using
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]))
})
Bug fixes
TS7016: Could not find a declaration file for module 'cookie'
- Fixes an outdated GitHub repository link in the
mockServiceWorker.js
file.
Assets
2
kettanaito released this
Bug fixes
- Fixes an issue that resulted into responses to
axios
requests not being mocked properly (#180, #181).
Internal
- Lists
node-request-interceptor
as an external dependency of themsw/node
bundle.
Assets
2
Features
- Custom request handlers have reworked lifecycle and accept new methods:
parse()
, to retrieve additional information about the request before the predicate.getPublicRequest()
, to modify the original request with public information (i.e. addingreq.params
orreq.variables
).
Bug Fixes
Assets
2
Features
- GraphQL requests are now being printed into browser’s console using a proper format (operation name / response status) (#161, #174)
- Each custom request handler can have its own
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.
Bug fixes
Assets
2
Bug fixes
Assets
2
Watchers:37 |
Star:4647 |
Fork:118 |
创建时间: 2018-11-13 22:58:44 |
最后Commits: 5天前 |
9c89476
Compare
Features