npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

msw-validate

v0.1.0

Published

Mock Service Worker Request Validation

Downloads

6

Readme

version(scoped) codecov

msw-validate

Mock Service Worker Request Validation

Mock Service Worker allows you to intercept requests and return mock responses from handlers. It works great for unit tests where mock handlers can be registered to verify application behavior for different responses.

But testing network calls should not be limited to just mocking responses. Validating that a particular endpoint was called with the correct params, headers, query, cookie or body is a must for a good unit test.

msw-validate allows you to declaratively define handlers that perform request validations, and also to easily setup per test scenarios. This library follows the msw best practice of asserting request validity by returning a error response when validation fails.

Quickstart

Define a handler and declare request assertions in the validate block

import { defineHttpHandler } from "msw-validate";

const handler = defineHttpHandler({
  method: "GET",
  url: "customer/:id/orders",
  validate: {
    "params.id": "1234",
    "query.status": ["ordered", "shipped"],
  },
  return: {
    orders: [{ id: 1, status: "shipped" }]
  }
});

Write the test

import { setupServer } from "msw/node";
import { orderService } from "services/order";

const server = setupServer();

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

describe("order service", () => {
  it("should fetch current orders", async () => {
    // register handler
    server.use(handler())

    const res = await orderService.getCurrentOrders("1234");
    const data = await res.json()
    expect(data.orders.length).toBe(1)
  })
})

If the order service incorrectly sends a ?status=canceled to the service, a 400 response will be returned with following details.

{
  path: "status",
  value: "canceled",
  error: 'expected ["ordered", "shipped"]'
}

Validation

More often than not, tests that verify requests or responses end up simply asserting that the data equals some deeply nested json (like a saved response from an actual call to an endpoint)

import expected from "./mocks/create-order.json";

expect(request.body).toEqual(expected);

Though these work great as regression tests, it is recommended to declare important expectations in the validate block.

Adding a few assertions automaticaly surfaces the actual intent of the code as opposed to a blob of data.

defineHttpHandler({
  validate: {
    "params.id": "1234",
    "cookies.promo": "BF2024",
    "query.status": ["ordered", "shipped"],
    "query.limit": (limit) => (limit > 0 && limit < 50) || "invalid limit",
    "headers.authorization": (auth) => auth === "Bearer secret" || HttpResponse.text(null, 403)
    "body.orders[1].description": "second order",
    "body": (data) => _.isEqual(data, jsonBlob)
  },
  return: { ... }
});

The Validation Object

  • Keys are paths to quickly get at the deeply nested field that needs to be checked
    • bruno-query is used to pick the value
      It has same syntax as lodash get with added array and deep navigation support
  • Only scalars and array of scalars are allowed as values, resulting in simple one line validations
  • Custom validation functions are allowed as in query.limit above
  • Custom error messages can be returned from validation functions
  • Custom responses can be returned as in headers.authorization above
  • Query and FormData are converted to objects with the qs package
  • A handler that expects form data can declare the requestBodyType: "form-data"
    • Do note that due to the following node bug you might need to pass --forceExit to jest
    • File uploads are not supported in this library, but can be enabled by writing a custom msw handler

Response

On success, the data or HttpResponse specified as return value is sent as a json response

Custom response functions can be specified and take the same argument as a msw resolver plus an invocation count.

This allows the same handler to return different responses for successive calls.

See below example from response.test.ts

const handler = defineHttpHandler({
  method: "GET",
  url: buildUrl("/test/:id"),
  validate: {},
  return: ({ params, invocation }) => {
    const response = { id: params.id, invocation };
    return invocation == 1 ? response : HttpResponse.json(response);
  },
});