Home / Blog / Mock the SellerMagnet API in TypeScript Tests Without Spending Credits

Mock the SellerMagnet API in TypeScript Tests Without Spending Credits

Test the typed code that calls the SellerMagnet API without hitting it: fake only `fetch`, typed as `typeof fetch` so a drift fails `tsc` before a test runs, and cover every billed, free and refunded status code with Vitest. No credits spent, no network call leaves the suite.

December 02, 2026
6 min read
SellerMagnet Team
Share & Bookmark
Terminal window showing a strict TypeScript compile and a Vitest run that fakes the SellerMagnet API's fetch call while the real typed client code runs unchanged

Mock the SellerMagnet API in TypeScript tests by faking only fetch, typed as typeof fetch itself rather than a hand-written interface: replace the one call the real sellermagnet.ts and retry.ts helpers make, script the status code and body each test needs, and run the unchanged, fully typed client code against it with Vitest. No credit is spent, no network call leaves the test, and typing the fake against the real global function's own signature makes a mock/reality drift a compile error, not a runtime surprise.

Key Takeaways

  • Type the fake as typeof fetch, not as a hand-written interface; a signature drift then fails tsc --noEmit before a single test runs.
  • Make the fake fail closed: a request before a test installs its scripted response should throw, not silently reach the real API.
  • A 429 is free and worth waiting out; a 500 is refunded and worth one retry; a 502/503 is billed on every attempt, so cap the attempts.
  • strict: true plus noUncheckedIndexedAccess in tsconfig.json turns buyBoxInfo.price's number | "N/A" union into a compile-time reminder to decode it, not a runtime NaN.
  • Count every call the fake received (mockFetch.CALLS.length) to verify the credit math of a scenario, not just its final return value.

Why not just call the real API in a TypeScript test suite?

Every SellerMagnet API request is billed per the table below, whether it comes from production code or a test. A CI run that fires on every push would spend credits on every build, a slow or flaky network turns a code bug into a failed pipeline, and a 404 or a 429 that a test wants to simulate on demand cannot be forced on the live API at all. A fake fetch makes every status code, including ones that are rare in practice, reproducible on every run, and the types stay checked the whole way through.

Scenarios worth testing, and what the fake needs to script for each.
ScenarioChargedRetry?Client should
happy pathbillednoparse and return
404 product not foundbillednoreport it; do not retry
free gate 400 (missing marketplaceId)freenofix the request, no retry
401 insufficient creditsfreenostop; top up credits
429 concurrency capfreeyessleep Retry-After, then retry
500 internal errorrefundedyesretry once, then stop
502 / 503 upstreambilledyesretry up to the attempt cap

How do I type the fake so a drift from the real fetch fails to compile?

Declare the fake as const fakeFetch: typeof fetch = async (input, init) => { ... } and assign it to globalThis.fetch. Because the variable's type comes from the real fetch global instead of a hand-written interface, any shape TypeScript's lib types give fetch (argument count, RequestInfo | URL first parameter, Promise<Response> return) is enforced on the fake too. api_key travels as a query parameter here, the same transport the TypeScript/JS quickstart uses; the fake asserts it is present on every call.

Measured, not assumed: a mock/reality drift fails tsc

Giving the fake fetch function above one extra required parameter (so its shape no longer satisfies typeof fetch) was tried against the exact files below. The result: tsc --noEmit exits 1 with TS2322: Type '(input: any, init: any, extra: string) => Promise<Response>' is not assignable to type ... Target signature provides too few arguments. Expected 3 or more, but got 2. Reverting the drift brings tsc --noEmit back to a clean exit 0, confirmed below.

Blueprint sequence diagram of a Vitest run faking the SellerMagnet API's fetch call while the real typed client code runs unchanged
Only fetch is faked; lookup() and getWithRetry() run unmodified, fully typed.

sellermagnet.ts - the real typed client under test, unmodified by the mock

// sellermagnet.ts - the real typed client under test, unmodified by the mock.
const API = "https://sellermagnet-api.com/api";

export class ApiError extends Error {
  readonly status: number;
  readonly retryAfter: number;
  constructor(status: number, message: string, retryAfter = 0) {
    super(`${status}: ${message}`);
    this.status = status;
    this.retryAfter = retryAfter;
  }
}

export interface ProductInfo {
  asin: string;
  title: string;
  price: number | null; // "N/A" on the wire must become null, never 0
  currency: string | null;
  rank: number | null;
  url: string;
}

interface ApiEnvelope<T> {
  success: boolean;
  data?: T;
  message?: string;
}

interface RawBuyBoxInfo {
  price: number | "N/A";
  currencyCode: string;
  sellerId?: string;
}

interface RawProduct {
  productInfo: {
    asin: string;
    title: string;
    buyBoxInfo: RawBuyBoxInfo;
    bestsellerRanks?: { main_category?: { rank: number } };
    link: string;
  };
}

export async function get<T>(endpoint: string, params: Record<string, string> = {}): Promise<T> {
  if (!process.env.SELLERMAGNET_API_KEY) throw new Error("Set SELLERMAGNET_API_KEY first");
  const url = new URL(`${API}/${endpoint}`);
  const query: Record<string, string> = { ...params, api_key: process.env.SELLERMAGNET_API_KEY };
  for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value);

  const res = await fetch(url, { signal: AbortSignal.timeout(120_000) });
  const body = (await res.json().catch(() => ({}))) as ApiEnvelope<T>;
  if (res.ok && body.success && body.data !== undefined) return body.data;
  const retryAfter = Number(res.headers.get("Retry-After")) || 0;
  throw new ApiError(res.status, body.message ?? "request failed", retryAfter);
}

function decodePrice(raw: number | "N/A" | undefined): number | null {
  return typeof raw === "number" ? raw : null;
}

export async function lookup(asin: string, marketplaceId: string): Promise<ProductInfo> {
  const { productInfo: p } = await get<RawProduct>("amazon-product-lookup", { asin, marketplaceId });
  return {
    asin: p.asin,
    title: p.title,
    price: decodePrice(p.buyBoxInfo?.price),
    currency: p.buyBoxInfo?.currencyCode ?? null,
    rank: p.bestsellerRanks?.main_category?.rank ?? null,
    url: p.link,
  };
}

retry.ts - the real typed retry wrapper under test, unmodified by the mock

// retry.ts - typed retry wrapper that respects billing: 429/500(once)/502/503 only.
import { ApiError, get } from "./sellermagnet.js";

const RETRYABLE = new Set([429, 500, 502, 503]);

export function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

export async function getWithRetry<T>(
  endpoint: string,
  params: Record<string, string> = {},
  attempts = 4,
): Promise<T> {
  let internalErrors = 0;
  for (let attempt = 1; attempt <= attempts; attempt++) {
    try {
      return await get<T>(endpoint, params);
    } catch (err) {
      if (!(err instanceof ApiError)) throw err;
      internalErrors += err.status === 500 ? 1 : 0;
      if (!RETRYABLE.has(err.status) || attempt === attempts || internalErrors > 1) throw err;
      const backoff = Math.min(2 ** attempt, 30);
      await sleep(Math.max(backoff, err.retryAfter) * 1000);
    }
  }
  // Unreachable: the loop above always returns or throws, but TypeScript's
  // control-flow analysis cannot prove that across a for-loop with an early
  // throw on the last attempt, so a sentinel keeps the typed return in sync
  // with every runtime path.
  throw new Error("unreachable");
}

mockFetch.ts - fakes fetch, typed as typeof fetch, fails closed

// mockFetch.ts - fakes only the global `fetch` type, the one call sellermagnet.ts
// and retry.ts make. Typed as `typeof fetch` itself, so a drift from the real
// fetch signature (wrong arg count, wrong return shape) is a compile error here,
// not just a runtime surprise discovered by a test. Fails closed.
process.env.SELLERMAGNET_API_KEY ??= "test-key";

export interface Call {
  endpoint: string;
  params: Record<string, string>;
}

export type Route = (endpoint: string, params: URLSearchParams) => [number, unknown, Record<string, string>?];

export const CALLS: Call[] = [];
let currentRoute: Route = blockedRoute;

function blockedRoute(): never {
  throw new Error("mockFetch: call install(route) first - no request may reach the real API");
}

export function install(route: Route): void {
  currentRoute = route;
}

export function reset(): void {
  currentRoute = blockedRoute;
  CALLS.length = 0;
}

export function ok(data: unknown): [number, unknown] {
  return [200, { success: true, data }];
}

export function error(
  status: number,
  message = "request failed",
  headers: Record<string, string> = {},
): [number, unknown, Record<string, string>] {
  return [status, { success: false, error: "error", message }, headers];
}

// The signature below must match `typeof fetch` exactly (minimal subset:
// RequestInfo/URL first arg, options with a signal). If a future real-fetch
// change narrows/widens that shape, `tsc` on this file fails before any test
// runs, catching a mock/reality drift the JS version can only catch at runtime.
const fakeFetch: typeof fetch = async (input, _init) => {
  const u = new URL(input instanceof URL ? input : input.toString());
  if (!u.searchParams.get("api_key")) throw new Error("api_key must travel as a query parameter");
  const endpoint = u.pathname.split("/").pop() ?? "";
  CALLS.push({ endpoint, params: Object.fromEntries(u.searchParams) });
  const [status, body, headers = {}] = currentRoute(endpoint, u.searchParams);
  return {
    ok: status >= 200 && status < 300,
    status,
    headers: { get: (k: string) => headers[k] ?? null } as Headers,
    json: async () => {
      if (typeof body === "string") throw new Error("not json"); // simulates an HTML error page
      return body;
    },
  } as Response;
};

globalThis.fetch = fakeFetch;
Blueprint table of test scenarios against the SellerMagnet API's status codes, billing and the correct client reaction
Each row needs its own scripted response; a happy-path test alone misses most of this.

What does a full Vitest scenario suite look like?

mockFetch.install(route) scripts one fake response per test, and an afterEach hook calls mockFetch.reset() so a scripted response can never leak into the next test. The 429 and 500 retry tests in this suite really wait out the backoff, the same way the Go and JavaScript mock-testing guides' tests do, rather than faking timers; that is why the suite below takes about ten seconds instead of milliseconds, a reasonable trade-off for a suite that is not run on every keystroke. vitest.config.ts was given testTimeout: 15000 so the 502 scenario's real backoff (two waits, about six seconds) has room to finish.

sellermagnet.test.ts - the scenario suite, run for real below

import { afterEach, test, expect } from "vitest";
import * as mockFetch from "./mockFetch.js";
import { ApiError, lookup } from "./sellermagnet.js";
import { getWithRetry } from "./retry.js";

const ASIN = "B0CL61F39H";
const MP = "ATVPDKIKX0DER";

function product(price: number | "N/A" = 444.99) {
  return {
    productInfo: {
      asin: ASIN,
      title: "PlayStation5 console (slim)",
      buyBoxInfo: { price, currencyCode: "USD" },
      bestsellerRanks: { main_category: { rank: 31 } },
      link: `https://www.amazon.com/dp/${ASIN}`,
    },
  };
}

afterEach(() => mockFetch.reset());

test("happy path parses the real response shape, typed end to end", async () => {
  mockFetch.install(() => mockFetch.ok(product()));
  const out = await lookup(ASIN, MP);
  expect(out).toEqual({
    asin: ASIN,
    title: "PlayStation5 console (slim)",
    price: 444.99,
    currency: "USD",
    rank: 31,
    url: `https://www.amazon.com/dp/${ASIN}`,
  });
  expect(mockFetch.CALLS).toHaveLength(1);
});

test('no featured offer price ("N/A") stays number | null, never 0', async () => {
  mockFetch.install(() => mockFetch.ok(product("N/A")));
  const out = await lookup(ASIN, MP);
  expect(out.price).toBeNull();
});

test("404 is billed and must not be retried", async () => {
  mockFetch.install(() => mockFetch.error(404, "Product not found."));
  await expect(getWithRetry("amazon-product-lookup", { asin: ASIN, marketplaceId: MP })).rejects.toMatchObject({
    status: 404,
  });
  expect(mockFetch.CALLS).toHaveLength(1);
});

test("free gate 400 missing marketplaceId is not retried", async () => {
  mockFetch.install(() => mockFetch.error(400, "Missing required parameter(s): marketplaceId"));
  const err: unknown = await getWithRetry("amazon-product-lookup", { asin: ASIN }).catch((e) => e);
  expect(err).toBeInstanceOf(ApiError);
  expect((err as ApiError).message).toContain("marketplaceId");
  expect(mockFetch.CALLS).toHaveLength(1);
});

test("401 insufficient credits is not retried", async () => {
  mockFetch.install(() => mockFetch.error(401, "Insufficient user credits."));
  await expect(
    getWithRetry("amazon-product-lookup", { asin: ASIN, marketplaceId: MP }),
  ).rejects.toMatchObject({ status: 401 });
  expect(mockFetch.CALLS).toHaveLength(1);
});

test("429 concurrency cap is free and retried, honours Retry-After", async () => {
  let calls = 0;
  mockFetch.install(() => {
    calls++;
    return calls === 1
      ? mockFetch.error(429, "Your plan (<Plan>) allows N concurrent requests. Retry shortly, or upgrade for more: https://sellermagnet-api.com/pricing", { "Retry-After": "2" })
      : mockFetch.ok(product());
  });
  const start = Date.now();
  const out = await getWithRetry<ReturnType<typeof product>>("amazon-product-lookup", {
    asin: ASIN,
    marketplaceId: MP,
  });
  expect(out.productInfo.asin).toBe(ASIN);
  expect(mockFetch.CALLS).toHaveLength(2);
  expect(Date.now() - start).toBeGreaterThanOrEqual(2000);
});

test("500 is refunded and retried exactly once, then stops", async () => {
  mockFetch.install(() => mockFetch.error(500, "Internal error."));
  await expect(
    getWithRetry("amazon-product-lookup", { asin: ASIN, marketplaceId: MP }),
  ).rejects.toMatchObject({ status: 500 });
  expect(mockFetch.CALLS).toHaveLength(2);
});

test("502 is billed on every attempt, retried up to the cap", async () => {
  mockFetch.install(() => mockFetch.error(502, "Upstream error."));
  await expect(
    getWithRetry("amazon-product-lookup", { asin: ASIN, marketplaceId: MP }, 3),
  ).rejects.toMatchObject({ status: 502 });
  expect(mockFetch.CALLS).toHaveLength(3);
});

test("fake fails closed without install: no request may reach the real API", async () => {
  await expect(fetch("https://sellermagnet-api.com/api/amazon-product-lookup?api_key=x")).rejects.toThrow(/install/);
});

npx tsc --noEmit -p tsconfig.json (strict mode, unmodified run)

npx tsc --noEmit -p tsconfig.json
(no output - strict mode, noUncheckedIndexedAccess, 0 errors, exit 0)

# Proof the mock is really type-checked against typeof fetch: giving fakeFetch
# one extra required parameter (so it no longer satisfies typeof fetch) and
# re-running the same command instead produces:
mockFetch.ts(46,7): error TS2322: Type '(input: any, _init: any, extra: string) => Promise<Response>' is not assignable to type '{ (input: URL | RequestInfo, init?: RequestInit | undefined): Promise<Response>; (input: string | Request | URL, init?: RequestInit | undefined): Promise<...>; }'.
  Target signature provides too few arguments. Expected 3 or more, but got 2.
mockFetch.ts(46,40): error TS7006: Parameter 'input' implicitly has an 'any' type.
mockFetch.ts(46,47): error TS7006: Parameter '_init' implicitly has an 'any' type.

# Reverting the extra parameter restores the clean exit 0 shown above.

npx vitest run --reporter=verbose output (unmodified run)

 ✓ sellermagnet.test.ts > happy path parses the real response shape, typed end to end 9ms
 ✓ sellermagnet.test.ts > no featured offer price ("N/A") stays number | null, never 0 1ms
 ✓ sellermagnet.test.ts > 404 is billed and must not be retried 3ms
 ✓ sellermagnet.test.ts > free gate 400 missing marketplaceId is not retried 2ms
 ✓ sellermagnet.test.ts > 401 insufficient credits is not retried 3ms
 ✓ sellermagnet.test.ts > 429 concurrency cap is free and retried, honours Retry-After 2008ms
 ✓ sellermagnet.test.ts > 500 is refunded and retried exactly once, then stops 2005ms
 ✓ sellermagnet.test.ts > 502 is billed on every attempt, retried up to the cap 6020ms
 ✓ sellermagnet.test.ts > fake fails closed without install: no request may reach the real API 28ms

 Test Files  1 passed (1)
      Tests  9 passed (9)
   Duration  10.49s (tests 99%)

Never hand-write a mock of sellermagnet.ts itself

A mock that reimplements lookup() or getWithRetry() tests the mock's own logic, not the real client, and a hand-written interface for the fake's own shape can quietly drift from fetch's real signature. Fake fetch itself, typed as typeof fetch, one level below your code, so a real bug in the parsing or retry logic still shows up as a failing test, and a signature drift shows up as a compile error instead.

Does the same pattern work for other HTTP clients or test runners?

Yes - fake the one function the real code calls to reach the network, typed as that function's own declared type, whatever the function or runner is. Jest works the same way: swap Vitest's vi.fn/global assignment for Jest's jest.spyOn(globalThis, "fetch"), keep the fake typed as typeof fetch, and the strict-mode guarantee carries over unchanged. The 429/Retry-After guide and the 502/503 retry guide are the production behaviour this test suite is checking against; keep all three in sync when the retry logic changes. Credit costs and the free trial are on the pricing page, and every endpoint's parameters are in the API documentation and code examples.

Frequently Asked Questions

Can my TypeScript tests call the real SellerMagnet API instead of mocking it?

They can, but every call is billed like any other request, a CI run that fires on every push burns credits fast, and a flaky network turns a code bug into a failed build. Faking only the fetch call keeps the real, typed client code under test while the API itself never sees a request.

What exactly should the mock type as, my own client's functions or fetch itself?

typeof fetch, never a hand-written interface for your own sellermagnet.ts. Typing the fake as the real global function's own type means a future change to fetch's signature, or a typo in the fake, fails tsc before a single test runs; a mock typed against your own client module can drift from reality and still compile.

Does strict mode actually catch a broken mock, or is that just a claim?

It is a measured result, not a claim: giving the fake fetch function one extra required parameter (so its shape no longer satisfies typeof fetch) makes tsc --noEmit fail with TS2322: Target signature provides too few arguments, caught at compile time, zero tests run. Revert the drift and the same tsc --noEmit exits 0.

How do I simulate a 429 concurrency cap without waiting seconds in every test run?

This suite does not fake timers, so the 429 and 500 retry tests really wait out the Retry-After and backoff, the same way the JavaScript mock-testing guide's tests do. If a faster suite matters more, wrap retry.ts's sleep() so a test can replace it with a no-op and assert on the duration it was called with instead.

Should the fake fetch allow a real request if a test forgets to configure it?

No. Make the default route throw immediately, and have each test install its own fake response before running the code under test. That way a forgotten setup fails the test loudly instead of quietly sending a real, billed request.

Bottom line: fake fetch typed as typeof fetch (or your language's equivalent one layer below the HTTP call), run the real typed client code against scripted responses for every billed, free and refunded status, and make the fake fail closed so a forgotten setup cannot send a real, billed request. The suite above runs strict tsc --noEmit clean and spends zero credits.

Ready to Extract Amazon Data at Scale?

Start building with SellerMagnet API today. Real-time product data, competitive pricing, and review analytics at your fingertips.

150 free API credits • No credit card required • Cancel anytime