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

netmock-js

v2.0.11

Published

A javascript network mocker for tests

Downloads

97

Readme

netmock

A javascript network mocker for tests

Installation

npm install --save-dev netmock-js

Usage

  import {netmock} from 'netmock-js';
  // mock some endpoint:
  netmock.post('https://wix.com', () => 'Mocked Text');
  
  // now calling fetch or axios on this endpoint will return the mocked body:
  const res = await fetch('https://wix.com', { method: 'POST' });
  const body = await res.text();
  expect(body).toBe('Mocked Text');

Setup

Add this to your jest config:

{
  "setupFilesAfterEnv": ['node_modules/netmock-js/lib/jest-setup.js']
}

API

netmock[method](url, handler): Netlog

The netmock object allows you to mock the following http method types: get/post/put/patch/delete. The returned object can be used for doing some assertions about the mocked endpoint (Read the section about netlog)

params:

  • url: string | route | RegExp

    netmock.get('https://wix.com/get/some/value', () => {}) // plain url
    netmock.get(/.*wix/, () => {}) // regex
    netmock.post('https://wix.com/bookings/:user/:id', () => {}) // route
    netmock.get('https://wix.com/get/some/value', (req, data) => ({responseNumber: data.callCount})) // different responses
       
    //using the returned endpoint log:
    const log = netmock.get('https://wix.com/get/some/value', () => {}) // plain url
    expect(log.callCount()).toEqual(0);

    In case of mock collisions, netmock will prefer plain url matching over regex matching over rout matching

  • handler: ({query, params}) => responseBody

    netmock.get('https://wix.com/get/some/value', () => ({id: 'mocked-id'})); // returning body
    netmock.post('https://wix.com/get/:id', (req) => ({id: req.params.id})); // using url params
    netmock.get('https://wix.com/get', (req) => ({id: req.query.id})); // using query params (when called like this: https://wix.com/get?id=mockedId)

resp(body: any) => NetmockResponse

In cases where you need to tweak the response parameters, for example the statusCode, your handler should return a response object like this:

   import {netmock, resp} from 'netmock-js';
   netmock.get('https://wix.com', () => resp({id: 'mocked-id'}).statusCode(400).delay(100));

Here is the NetmockResponse object API:

  • statusCode(value: number); // set the response status
  • headers: (value: object); // set the response header
  • delay(delayInMs: number); // simulate response delay
  • set: (set: (value: Partial)); //a convenient function for setting multiple response fields at once

netlog(method, url) => ProbObject

A function that allows you to access the logs of a certain endpoint and do some assertions on them.

params:

  • method: string - The http method of the mocked endpoint (post, get, put, patch, delete);
  • url: string | route | regex - The url of the mocked endpoint;

It returns and object with the following methods:

  • callCount() - returns the number of times the endpoint has been called.
  • getRequest(index: number) - returns the request object for the given call number.

usage:

    import {netlog} from 'netmock-js';
    const mockedEndpointUrl = 'https://www.wix.com/:id/:user';
    netmock.post(mockedEndpointUrl, () => ({}));
    await fetch('https://www.wix.com/123/blamos', { method: 'post' }); //trigger call 1
    await fetch('https://www.wix.com/456/blamos2?value=true', { method: 'post' }); //trigger call 2
    expect(netlog('post', mockedEndpointUrl).callCount()).toEqual(2);
    expect(netlog('post', mockedEndpointUrl).getRequest(0).params).toEqual({ id: '123', user: 'blamos' });
    expect(netlog('post', mockedEndpointUrl).getRequest(1).query).toEqual({ value: 'true'});

Using with axios:

Netmock attempts to automatically detect if you are using Axios and applies the relevant mocks for you. However, if you have multiple instances of Axios in your node_modules, you need to explicitly specify which Axios instance netmock should mock:

//inside jest-setup file:
import {mockAxios} from 'netmock-js';
beforeEach(() => {
   mockAxios(require('axios'));
});

Configurations:

allowRealNetwork: boolean | RegExp

Netmock will block any real network by default. In order to allow real network requests (to unmocked endpoints), you can do the following:

import {configure} from 'netmock-js;
beforeEach(() => {
  configure({
    allowRealNetwork: true;
  })
});

You can pass a regex instead of boolean in order to allow real network only for specific urls (those who match the regex). Allowing real network in your tests is not recommended, and can lead to flaky tests. This why netmock will disable this option for you after each test, and if you want to allow real network requests for all tests, make sure to call allowRealNetwork(true) inside beforeEach().

suppressQueryParamsInUrlWarnings: boolean

Will suppress any warnings regarding passing query params in the mocked url