msw

Seamless REST/GraphQL API mocking library for browser and Node.js.

MIT License

Downloads
15.7M
Stars
14.9K
Committers
153

Bot releases are hidden (Show)

msw -

Published by kettanaito over 3 years ago

Breaking changes

  • The Promise returned by worker.start() will now reject in the case of any errors during the worker registration (#607).
  • The library no longer exports the following TypeScript declarations:
    • RestRequestType, use RestRequest instead.
    • GraphQLMockedRequest, use GraphQLRequest instead.
    • GraphQLMockedContext, use GraphQLContext instead.
    • GraphQLRequestPayload, use GraphQLRequestBody instead.
    • GraphQLRequestParsedResult, use ParsedGraphQLRequest instead.
    • GraphQLResponseResolver
  • The values of the MockedRequest type no longer have the params key (#561). Please use the RestRequest type to annotate REST API requests instead.

Features

  • Supports automatic worker script updates (#606). Respects the 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.

  • When running 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.
  • Intercepts requests originating from an iframe (#589).
  • Adds virtual cookie store to ensure the persistency of cookies received from the same domains across multiple requests (#435, #469).

Bug fixes

  • Fixes an issue when a request body type generic had no effect on the response composition chain validation.
  • Fixes an issue when a 204 response threw an exception when the library emitted its response:* life-cycle events (#570).

Internal

  • Rebuilds the Request Handler API from ground-up (#561). Does not introduce any breaking changes in how you use the handlers.
  • Fixes the auto-imports of the library’s methods suggested by IDE (#598).
  • Updates the dependencies.
msw -

Published by kettanaito over 3 years ago

Bug fixes

  • Fixes an issue that resulted in GraphQL request handlers not annotating the mocked response structure based on the given generic type (#587).
  • Fixes an issue when a one-time request handler (res.once) affected multiple matching requests made in parallel (#583).
  • Properly exports the renamed OnUnhandledRequest type as the new UnhandledRequestStrategy type (#577).
msw -

Published by kettanaito over 3 years ago

Features

  • onUnhandledRequest option will now suggest similar request handlers based on the URL/operation name similarity (#560).

Bug fixes

  • Fixes an issue that resulted in a 202 status response throwing an exception when the library attempted to re-create its Response instance for the response:* life-cycle event (#570).
  • Fixes an issue when a request handler stack trace wasn't handled properly on Windows machines (#566).
  • Fixes an issue when using the 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.
msw -

Published by kettanaito over 3 years ago

This release introduces changes to the mockServiceWorker.js file. Please follow the instructions in the browser to update the worker file. Thank you.

Features

  • Adds support for GraphQL upload and multipart data operations (#215, #543).
  • Adds delay modes: “real” and “infinite” (#538). Supports infinite loading.
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)
  • Displays [MSW] Mocking disabled message when calling worker.stop(). (#485, #493).

Bug fixes

  • Fixes an issue that resulted in theFailed 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.
  • Fixes an issue that resulted in an exception being thrown when handling subsequent requests in Safari (#558, #565).
  • Fixes an issue when the ExecutionResult of graphql was not compatible with ctx.data and ctx.errors utilities (#522, #542).
  • Fixes an issue that resulted in the MSW worker handling unrelated message event originating from other tools (#551).

Internal

  • Updates dependencies to their latest versions.
  • Consistently uses self instead of this in the worker script (#568).
  • Ensures that MSW doesn’t handle events originating from unrelated workers (#551).
msw -

Published by kettanaito almost 4 years ago

Features

  • Adds Life-cycle events API (#482, docs).
msw -

Published by kettanaito almost 4 years ago

Features

  • Exports the RestContext type interface for public consumption (#524).
msw -

Published by kettanaito almost 4 years ago

Features

  • Publishes the library in IIFE format, allowing to use it from a <script> tag (#507, #509).

Internal

  • Updates package's dependencies (#521).
msw -

Published by kettanaito almost 4 years ago

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.
msw -

Published by kettanaito almost 4 years ago

Breaking changes

  • ctx.json context utility now always stringifies the response body (#468).
  • Removes JSON response body transformer as the default response body transformer. Nothing implicitly transforms the response body now.

Migration guidelines

  • Replace custom response transformers that might have affected the end response body, such as custom serializers, with custom response transformers.

Bug fixes

  • Fixes an issue that resulted in a response body being stringified twice (#466).
msw -

Published by kettanaito almost 4 years ago

Features

  • Supports asynchronous response transformers (#465, #467).
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'
msw -

Published by kettanaito almost 4 years ago

Features

msw -

Published by kettanaito almost 4 years ago

Bug fixes

  • Fixes an issue that resulted into a "Duplicate parameter" exception in Safari (#470).
  • Fixes an issue where the setupServer function had no explicitly provided return type signature (#458).
msw -

Published by kettanaito almost 4 years ago

Bug fixes

  • Fixes an issue that resulted into Content-Type: application/json request body not being parsed as a JSON whenever it had an additional charset header value (#462, #463).

Internals

  • Updates package dependencies.
msw -

Published by kettanaito almost 4 years ago

Breaking changes

Features

  • Supports setting both 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' }
    ])
  )
})
  • Supports creation of custom response transformers (#440, #441).

Bug fixes

  • Fixes an issue that resulted into inferred response status texts always set to "OK" (#438).
msw -

Published by kettanaito about 4 years ago

Features

  • Adds support for type annotation of path parameters (#393, #421).
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 the GraphQLRequestParsedResult type from the package (#425).
msw -

Published by kettanaito about 4 years ago

Bug fixes

  • Fixes type annotations of ResponseTransformer to drop the usage of the unknown generics causing type violations in strict mode (#381, #382).
msw -

Published by kettanaito about 4 years ago

Bug fixes

  • Fixes an issue that resulted into TypeScript violations in strict mode (#377, #379).
msw -

Published by kettanaito about 4 years ago

This release contains changes to the mockServiceWorker.js file. Please follow the instructions in your browser to upgrade the Service Worker file.

Breaking changes

  • 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()

Features

  • Adds support for mocking any GraphQL operation regardless of its type via 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 })
})
  • Adds support for request and response body type generics to 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]))
})
  • Adds support to rest.head() request handler to match HEAD method requests (#356).
  • Adds findWorker option to worker.start() to locate the mock Service Worker script at a custom location (#335, #351).
  • Adds a keepalive mechanism between a client and the Service Worker to prevent the worker to be terminated due to inactivity (#367, #371).
  • ctx.json now supports any data types that can be serialized to a valid JSON (#349, #350).

Bug fixes

  • Fixes an issue that resulted into custom options to worker.start() not being deeply merged with the default ones (#347, #348).
  • Fixes an issue that resulted into ctx.json() utility function accepting only objects. Now it accepts any data that can be stringified into JSON (#349, #350).
  • Fixes an issue that resulted into “The “superCtor” argument must be of type function
    ”error message when using setupServer (https://github.com/mswjs/node-request-interceptor/issues/49, https://github.com/mswjs/node-request-interceptor/pull/50).
  • GET and HEAD requests now forcefully contain no request body (#361, #366).

Internals

  • Adjusts internal tooling to support contributors with Windows machines (#363, #364).
  • Updates dependencies (#376).
msw -

Published by kettanaito about 4 years ago

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 version 0.3.5 (see Changelog).
msw -

Published by kettanaito about 4 years ago

Bug fixes

  • Fixes an issue that produces a "Must provide source" error during GraphQL parsing of POST requests with body, but without the query property (#234, #328, #329).
  • Fixes an issue that resulted into http module being patched in React Native environment, where it's not present (#203, #331).

Dependencies