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

yet-another-fetch-mock

v4.2.1

Published

[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier) [![codecov](https://codecov.io/gh/nutgaard/yet-another-fetch-mock/branch/master/graph/badge.svg)](https://codecov.io/gh/nutgaard/

Downloads

70

Readme

Yet-Another-Fetch-Mock

styled with prettier codecov dependencies Status

Installation

npm install yet-another-fetch-mock --save-dev

Setup

const loggingMiddleware: Middleware = (request, response) => {
  console.log('response', response);
  return response;
}


const mock = FetchMock.configure({
  enableFallback: true, // default: true
  middleware: loggingMiddleware // default: (req, resp) => resp
});


const delayedErrorMock = FetchMock.configure({
  middleware: MiddlewareUtils.combine(
    MiddlewareUtils.delayMiddleware(200),
    MiddlewareUtils.failurerateMiddleware(0.2)
  )
});

Examples

mock.get('/my-url', (req, res, ctx) => res(ctx.json({ key: 'value' }))); // Returns the object as the json-response
mock.post('/another-url', (req, res, ctx) => res(ctx.json({ key: 'result of posting' })));


// Creating dynamic content based on url
mock.put('/api/:id/app', (req, res, ctx) => {
  // `req` contains the original parameters to `fetch`,
  // and in addition: url, http-verb, path parameters and query parameters
  // `res` is used for combining and build your response based on helpers from `ctx`
  return res(
    ctx.json({id: req.pathParams.id, content: 'Some random content'})
  ); 
});


// More advanced route-matching
mock.mock(
  MatcherUtils.combine(
    MatcherUtils.method('HEAD'),
    MatcherUtils.url('/custom-url'),
    // Your custom matcher here
  ),
  (res, req, ctx) => res(
    ctx.delay(1000),
    ctx.json({ data: 'lots of data' })
  )
);

// Combining resultsUtils
mock.get('/test/:id', (req, res, ctx) => res(
  ctx.delay(1000),
  ctx.header('X-My-Header' ,'HeaderValue'),
  ctx.json({ requestId: req.pathParams.id })
));

Teardown

mock.restore();

Usage in tests

The library ships with a custom Middleware that allows for introspection of intercepted fetch-calls.

The spy exposes seven diffrent methods, six (middleware is used for setup) of which can be used to verify that a call has been intercepted. All methods accept an optional argument of the type RouteMatcher which can be created using the MatcherUtils. In cases where you don't send in an RouteMatcher, then a default "match-everything"-matcher is used.

Example

import FetchMock, { MatcherUtils, SpyMiddleware } from 'yet-another-fetch-mock';

describe('test using yet-another-fetch-mock', () => {
  let mock: FetchMock;
  let spy: SpyMiddleware;
  
  beforeEach(() => {
    spy = new SpyMiddleware();
    mock = FetchMock.configure({
      middleware: spy.middleware
    });
    expect(spy.size()).toBe(0);
  });
  
  afterEach(() => {
    mock.restore();
  });
  
  it('should capture calls', (done) => {
      mock.get('/test/:id', (req, res, ctx) => res(ctx.json({ data: 'test' })));
      Promise.all([
        fetch('/test/121'),
        fetch('/test/122')
      ])
        .then(() => {
          expect(spy.size()).toBe(2);
          expect(spy.lastCall()).not.toBeNull();
          expect(spy.lastUrl()).toBe('/test/122');
          expect(spy.called(MatcherUtils.url('/test/:id'))).toBe(true);
          done();
        })
    });
});

Typescript

Full documentation of types can be seen here, or here if you prefer reading typescript code.

Tips

It is recommended to toggle the fetch-mock functionality behind an environment variable, as to allow uglify/envify (or similar) to remove the code for production builds.

As an example;

if (process.env.USE_MOCK_SETUP === 'true') {
  require('./mocks')
}

Credits

Made using the awesome typescript library starter