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 🙏

© 2026 – Pkg Stats / Ryan Hefner

jest-api-mock

v1.0.6

Published

![npm downloads](https://img.shields.io/npm/dw/jest-api-mock)

Readme

Jest Api Mock

npm downloads

Jest api mock is an easier way to configure mock api's for your api services. It's easy to setup and you don't need any complex setup. It leverages Jest's to provide a central config file for mocking all your api calls. You could see its magic especially when you have a complex heirarchy of api calls in your application and you wan't to configure them based on various parameters.

You could refer to the blogPost - mocking-apis-with-jest and jest-api-mock to know more on how this package works.

Contents

Installation and Setup

Package Installation

To setup your fetch mock you need to do the following things:

$ npm install --save-dev jest-api-mock

Create a setupJest file to setup the mock or add this to an existing setupFile. :

Create a setupFile in case you don't already have one.

Create a setupFile and add the setupFile to your jest config in package.json:

"jest": {
  "automock": false,
  "setupFiles": [
    "./setupJest.js"
  ]
}

Add the following lines to your setupFile

//setupJest.js or similar file
import "jest-api-mock";

With this, you should have access to a global variable jestApiMock. Now you need to tell jestApiMock, what path needs to be mocked. You would want to give abolute path of your service file which you are using to do api call.

const path = require("path");
jestApiMock.mockApiService(path.resolve("./src/api"));

With this your setup is done. All thats required now is to tell what service needs to be mocked and how.

jestApiMock.urlMapper([
  {
    url: <api__path_to_mock>,
    get: <url_handler> // This is a function which you have written to handle apis ending with /todos/1
  },
  {
    url: <api__path_to_mock>,
    get: require('<path_to_file_with_response>') // This is the mock api response
  },
  {
    url: <api__path_to_mock>,
    post: <url_handler> // This is a function which you have written to handle apis ending with todos/addTodo of type post
  }
])

url_handler - This is a function which will be called whenever the api is invoked. api__path_to_mock - You could give the entire string or give regex for more extensive comparison.

We will be referring to urlHandler throughout this document.

Sample of the complete setup

The entire structure looks something like below in your setupFile. If you already have a setup file with lot of configuration, its preferred to create another setupFile for better readability.

// This is a sample of the setup file - apiMockerSetup.js.
import "jest-mock-api";
import todoHandler from "./mocks/todoGetHandler";
import todoPostHandler from "./mocks/todoPostHandler";
const path = require("path");
jestApiMock.mockApiService(path.resolve("./src/api"));
jestApiMock.urlMapper([
  {
    url: /[\w.]*\/todos\/1/i,
    get: todoHandler // This is a function which you have written to handle apis ending with /todos/1
  },
  {
    url: /[\w.]*\/user/i,
    get: require("./mocks/raw/userInfo") // This is the mock api response
  },
  {
    url: /[\w.]*\/todos/i,
    post: todoPostHandler // This is a function which you have written to handle apis ending with todos/addTodo of type post
  }
]);

Available api's

  • jestApiMock.updateParams()[Optional] - Add params which will be sent to your urlhandler.

Example

This is especially useful to send custom mock response based on your test suite. You could either use it at the top of your file or for each test suite.

import { getUser } from "./store/user";

describe("This is a mock test suite", () => {
  beforeAll(() => {
    // This will be available in the url handler functions which are called to get the mocks
    jestApiMock.updateParams({
      user: "admin"
    });
  });

  it("should return true", () => {
    getUser().then(resp => {
      expect(resp.user).toEqual("admin");
    });
  });
});

Please refer to the example section to see how to access the params in the urlHandler.

Accessing paramaters in urlHandler

The parameters recieved by urlHandler functions are as follows

{
  genericParams, //Params passed to jestApiMock by calling `jestApiMock.updateParams()` api
  apiParams, //These are params sent during api call, could be especially useful if you want to customize the response based on params sent during POST,DELETE and PUT calls.
}

Example

//userHandler.js
const userHandler = (url,data) => {
  let isAdmin = false;
  if(data.genericParams && data.genericParams.user === 'admin') {
    isAdmin = true;
  }
  return {
      todos:[...],
      isAdmin,
      version:'1',
      id:'asu3-1404-jfdfs-23id'
  }
}

export default apiHandler;

Known issues

  • doing jest.resetModules() resets all currently available modules. Since we use jests doMocks to mock api's, the mock gets reset and will not run for that test file.
  • Presently we can only mock for api services designed in axios style, like in the format below
{
  get,
  post,
  delete,
  put
}

We would like to extend this further to support anytype of api service