Getting Started
Mentoss is a utility for mocking JavaScript fetch()
requests both in the browser and on server runtimes like Node.js, Deno, and Bun. All of these environments have a global fetch()
function capable of making HTTP requests. When testing your JavaScript code, you don’t want to make network requests, so Mentoss is used to simulate those requests and their responses.
-
Install Mentoss. If you’re using Mentoss in a server-side runtime, you can install it using the package manager of your choice.
Install Dependencies npm install mentoss -DInstall Dependencies pnpm add mentoss -DInstall Dependencies yarn add mentoss -DInstall Dependencies bun install mentoss -D -
Create a mock server. Import the
MockServer
constructor from Mentoss and create a new instance like this:import { MockServer } from "mentoss";const server = new MockServer("https://api.example.com");The
server
object is where you can set up the routes that you want to mock. For example:import { MockServer } from "mentoss";const server = new MockServer("https://api.example.com");// example routeserver.get("/ping", 200);This example creates a route of
/ping
that returns a 200 status when called.Mock servers can specify routes in a number of different ways. See XXX for more details.
-
Create a fetch mocker. A
FetchMocker
instance is used to create a mocked version of thefetch()
function. To create a fetch mocker, import theFetchMocker
constructor and specify the server(s) you want to use:import { MockServer, FetchMocker } from "mentoss";const server = new MockServer("https://api.example.com");const mocker = new FetchMocker({servers: [server],});Once you have a fetch mocker created, it’s time to use the mocked
fetch()
function. -
Use the mocked
fetch()
function. CallmockGlobal()
and then usefetch()
as you normally would:import { MockServer, FetchMocker } from "mentoss";import { expect } from "chai";describe("My API", () => {let mocker;const server = new MockServer("https://api.example.com");mocker = new FetchMocker({servers: [server]});before(() => {mocker.mockGlobal();});// reset the server after each testafterEach(() => {mocker.clearAll();});after(() => {mocker.unmockGlobal();});it("should return a 200 status code", async () => {// set up the route to testserver.get("/ping", 200);// make the requestconst response = await fetch("https://api.example.com/ping");// check the responseexpect(response.status).to.equal(200);});});