Coder Social home page Coder Social logo

separaterecords / deno_mock_fetch Goto Github PK

View Code? Open in Web Editor NEW
10.0 2.0 1.0 11 KB

Use URLPattern syntax to mock fetch responses

Home Page: https://doc.deno.land/https/deno.land/x/mock_fetch/mod.ts

License: MIT License

TypeScript 100.00%
deno fetch-mock mock-fetch typescript

deno_mock_fetch's Introduction

deno_mock_fetch

An extremely simple way to mock globalThis.fetch.

Read the documentation, or see "Usage" below.

Usage

1. Setup

Import the library and install the mock. Any fetches after calling install() will throw an error if you haven't explicitly added a mock for that route.

import * as mf from "https://deno.land/x/[email protected]/mod.ts";

// Replaces globalThis.fetch with the mocked copy
mf.install();

2. Mocking routes

Call mock with a route (optionally starting with a method specifier, eg. DELETE@) and a function (can be async). Whenever that route is fetched, the function will be executed and the response will be returned.

The route uses URLPattern, which allows you to match patterns and wildcards.

Only the path name will be used to match a handler, so you can use literally anything for the host when fetching.

mf.mock("GET@/api/hello/:name", (_req, params) => {
  return new Response(`Hello, ${params["name"]}!`, {
    status: 200,
  });
});

const res = await fetch("https://localhost:1234/api/hello/SeparateRecords");
const text = await res.text(); //=> "Hello, SeparateRecords!"

3. Teardown

You can remove a single route's handler with remove, or reset all handlers with reset. Once the handler has been removed, that route will go back to throwing.

mf.remove("GET@/api/hello/:name");
// OR: mf.reset()

await fetch("https://example.com/api/hello/world");
// UnhandledRouteError: GET /api/hello/world (0 routes have handlers)

To restore the original fetch, call uninstall.

mf.uninstall();

Advanced usage

You don't have to replace the global fetch, or even have global state, by using the sandbox function. The returned object provides the same methods as the module (minus install & uninstall). Calling these methods will not alter global state.

// Ky is an excellent and easy-to-use fetch wrapper.
import ky from "https://cdn.skypack.dev/ky?dts";

// This object can also be destructured.
const mockFetch = mf.sandbox();

// Make a ky instance that uses mocked fetch - never touching the global fetch.
// Using a prefix URL means you won't need to write the URL every time.
const myKy = ky.extend({
  fetch: mockFetch.fetch,
  prefixUrl: "https://anyurlyouwant.com",
});

// Now you can mock the routes like normal
mockFetch.mock("PUT@/blog/posts", async (req) => {
  return new Response(/* ... */);
});

myKy.put("blog/posts", {
  /* ... */
});

You can destructure it, too.

const { fetch, mock, remove, reset} = mf.sandbox();

Credits

@eliassjogreen's tiny router (source) does the bulk of the work. It's general-purpose, but works great for Deno Deploy.

deno_mock_fetch's People

Contributors

clo4 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

eliassjogreen

deno_mock_fetch's Issues

Update deps!

Hiya! Randomly stumbled upon this when I needed a mock-fetch module for work and this looks awesome! Thanks for the credit btw, was kinda shook when I read the README and all of the sudden my name and project pops up in the credits ๐Ÿ˜„. But yeah, like the title says it would be nice if you would update router to version 0.0.12.

New API

Some requirements for the new API

  • Needs to track how many times a route is fetched
    • An assert to ensure it's fetched exactly, at least, or at most, N times
  • Needs ability to un-mock a route after fetching it N times

It might be easier to vendor the dependency on router for this so there's no duplication! Can also use a different syntax, instead of GET@/... it can use GET /...

Mock once feature

Hey, it would be very convient to have a utility function to mock the route and remove the route straight after it gets 1 call. Maybe even a mock_n one.

Can you simulate an `AbortController` timeout?

I'm trying to use this to test my retry fetch util, but it doesn't seem to be working. I can see the timeout is being called, but it doesn't seem to timeout the request. Do you know if this is possible to test?

Code

const {timeout = 10000} = options;

const controller = new AbortController();
const id = setTimeout(() => {
    controller.abort();
}, timeout);

res = await fetch(url, {
    ...options,
    signal: controller.signal
});
clearTimeout(id);

Test

let called = 0;

mf.mock("GET@/api/hello/:name", async (_req: Request, params: any) => {
    if (called++ === 0) {
        await sleep(2);
        return new Response();
    }

    return new Response(`Hello, ${params["name"]} ${called}!`, {
        status: 200,
    });
});

const res = await retryFetch("https://localhost:1234/api/hello/SeparateRecords", {timeout: 1000});
assertEquals(2, called);
assertEquals('Hello, SeparateRecords 2!', await res.text());

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.