Tapico / tapico-msw-webarchive

An utility to drive requests handlers through a `.har` web-archive file
MIT License
99 stars 8 forks source link
mock msw

@tapico/msw-webarchive

A utility to drive requests handlers through a .har web-archive file for the Mock Service Worker library. This utility allows you to mock server handlers by using .har web-archive file which can be created by using applications like Charles, ProxyMan or the Chrome Developer Tools.

Why you use this?

We have been using it during the development of web-applications, while the backend API endpoints weren't available yet or when we want to reproduce a problem of a customer. This way we can request the customer to send us a .har web-archive file and let this file drive the network requests to our back-end, this has greatly eased reproducing problems reported.

Getting started

To use this library you need to have a HAR (*.har) file generated from the network traffic of your application. Follow the instructions below to learn how to do that.

Install

npm install @tapico/msw-webarchive --save-dev

Install Mock Service Worker

Follow the Installation instructions from the Mock Service Worker documentation.

Create a HAR file

Chrome

Chrome DevTools HAR export

Firefox

Firefox DevTools HAR export

Generate request handlers

import { setupWorker } from 'msw'
import { setRequestHandlersByWebarchive } from '@tapico/msw-webarchive'
import * as traffic from './example.har'

const worker = setupWorker()
setRequestHandlersByWebarchive(worker, traffic)

worker.start()

Options

quiet: boolean

Disables the logging of debugging messages of the library.

setRequestHandlersByWebarchive(worker, har, {
  quiet: true,
})

strictQueryString: boolean

Stricly match a request URL query parameters during request URL matching. When set to false, request URL query parameters are ignored during matching.

setRequestHandlersByWebarchive(worker, har, {
  strictQueryString: false,
})

resolveCrossOrigins: (origin: string) => string

Override the Access-Control-Allow-Origin response header whenever it's present.

setRequestHandlersByWebarchive(worker, har, {
  resolveCrossOrigins(origin) {
    return '*'
  },
})

domainMappings: Record<string, string>

Allow mapping the domains in your har file to something else. This may be useful if you are making relative requests against the origin (eg. fetch('/hello')), you may want to use a domainMapping configuration like:

setRequestHandlersByWebarchive(worker, har, {
  domainMappings: {
    'http://example.com': 'http://localhost',
  },
})

responseDelay: 'real' | 'none' | ResponseDelayFunction

Controls the mock response delay behavior.

setRequestHandlersByWebarchive(worker, har, {
  responseDelay: 'none'
})
setRequestHandlersByWebarchive(worker, har, {
  responseDelay: (timeDelay: number, requestContext: Request) => {
    if (requestContext.url === 'http://example.com') {
      return timeDelay * 2
    }
    return 0
  }
})