Mock the SellerMagnet API in Node.js tests by faking only global.fetch, never your own client module: replace the one call the real sellermagnet.mjs and retry.mjs helpers make, script the status code and body each test needs, and run the unchanged client code against it with Node's built-in node:test runner. No npm package, no credit is spent, no network call leaves the test, and the exact parsing and retry logic under test is the code that ships.
Key Takeaways
- Patch
global.fetchonly; a hand-written mock of your own client module can drift from the real one and still pass. - 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.
- Node 18+ ships
fetch,AbortSignal.timeoutandnode:testbuilt in, so this whole suite needs zero npm installs. - Count every call the fake received (
mockApi.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 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.
| Scenario | Charged | Retry? | Client should |
|---|---|---|---|
| happy path | billed | no | parse and return |
| 404 product not found | billed | no | report it; do not retry |
| free gate 400 (missing marketplaceId) | free | no | fix the request, no retry |
| 401 insufficient credits | free | no | stop; top up credits |
| 429 concurrency cap | free | yes | sleep Retry-After, then retry |
| 500 internal error | refunded | yes | retry once, then stop |
| 502 / 503 upstream | billed | yes | retry up to the attempt cap |
How do I fake just fetch, not my own code?
Replace globalThis.fetch with an async function that returns a scripted status, JSON body and headers, then let sellermagnet.mjs's get() and retry.mjs's getWithRetry() run exactly as they would in production. The fake defaults to throwing, so a test that forgets to script a response fails loudly instead of letting a real, billed request through. api_key travels as a query parameter here, the same transport the Node.js quickstart uses; the fake asserts it is present on every call.

sellermagnet.mjs - the real client under test, unmodified by the mock
const API = "https://sellermagnet-api.com/api";
export class ApiError extends Error {
constructor(status, message, retryAfter = 0) {
super(`${status}: ${message}`);
this.status = status;
this.retryAfter = retryAfter;
}
}
export async function get(endpoint, params = {}) {
if (!process.env.SELLERMAGNET_API_KEY) throw new Error("Set SELLERMAGNET_API_KEY first");
const url = new URL(`${API}/${endpoint}`);
const query = { ...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(() => ({}));
if (res.ok && body.success) return body.data;
const retryAfter = Number(res.headers.get("Retry-After")) || 0;
throw new ApiError(res.status, body.message ?? "request failed", retryAfter);
}
export async function lookup(asin, marketplaceId) {
const { productInfo: p } = await get("amazon-product-lookup", { asin, marketplaceId });
return {
asin: p.asin,
title: p.title,
price: typeof p.buyBoxInfo?.price === "number" ? p.buyBoxInfo.price : null, // "N/A" must become null
currency: p.buyBoxInfo?.currencyCode ?? null,
rank: p.bestsellerRanks?.main_category?.rank ?? null,
url: p.link,
};
}
retry.mjs - the real retry wrapper under test, unmodified by the mock
import { ApiError, get } from "./sellermagnet.mjs";
const RETRYABLE = new Set([429, 500, 502, 503]);
export async function getWithRetry(endpoint, params = {}, attempts = 4) {
let internalErrors = 0;
for (let attempt = 1; attempt <= attempts; attempt++) {
try {
return await get(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);
}
}
}
export function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
mock_api.mjs - fakes only global.fetch, fails closed
// Fakes only global.fetch, the one call sellermagnet.mjs / retry.mjs make.
// Fails closed: any fetch before a test installs its route throws.
process.env.SELLERMAGNET_API_KEY ??= "test-key";
export const CALLS = [];
let currentRoute = blockedRoute;
function blockedRoute() {
throw new Error("mock_api: call install(route) first - no request may reach the real API");
}
export function install(route) {
currentRoute = route;
}
export function reset() {
currentRoute = blockedRoute;
CALLS.length = 0;
}
export function ok(data) {
return [200, { success: true, data }];
}
export function error(status, message = "request failed", headers = {}) {
return [status, { success: false, error: "error", message }, headers];
}
globalThis.fetch = async (url) => {
const u = new URL(url);
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) => headers[k] ?? null },
json: async () => {
if (typeof body === "string") throw new Error("not json"); // simulates an HTML error page
return body;
},
};
};

What does a full node:test scenario suite look like?
mockApi.install(route) scripts one fake response per test, and an afterEach hook calls mockApi.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 mock-testing guide's tests do, rather than faking setTimeout; that is why the suite below takes about ten seconds instead of milliseconds, and it is a reasonable trade-off for a suite that is not run on every keystroke.
sellermagnet.test.mjs - the scenario suite, run for real below
import { test, beforeEach, afterEach } from "node:test";
import assert from "node:assert/strict";
import * as mockApi from "./mock_api.mjs";
import { ApiError, lookup } from "./sellermagnet.mjs";
import { getWithRetry, sleep } from "./retry.mjs";
const ASIN = "B0CL61F39H", MP = "ATVPDKIKX0DER";
function product(price = 444.99) {
return {
productInfo: {
asin: ASIN, title: "PlayStation5 console (slim)",
buyBoxInfo: { price, currencyCode: "USD" },
bestsellerRanks: { main_category: { name: "Video Games", rank: 31 } },
link: `https://www.amazon.com/dp/${ASIN}`,
},
};
}
afterEach(() => mockApi.reset());
test("happy path parses the real response shape", async () => {
mockApi.install(() => mockApi.ok(product()));
const out = await lookup(ASIN, MP);
assert.deepEqual(out, { asin: ASIN, title: "PlayStation5 console (slim)", price: 444.99,
currency: "USD", rank: 31, url: `https://www.amazon.com/dp/${ASIN}` });
assert.equal(mockApi.CALLS.length, 1);
});
test('no featured offer price ("N/A") is not a number', async () => {
mockApi.install(() => mockApi.ok(product("N/A")));
const out = await lookup(ASIN, MP);
assert.equal(out.price, null);
});
test("404 is billed and must not be retried", async () => {
mockApi.install(() => mockApi.error(404, "Product not found."));
await assert.rejects(() => getWithRetry("amazon-product-lookup", { asin: ASIN, marketplaceId: MP }),
(err) => err instanceof ApiError && err.status === 404);
assert.equal(mockApi.CALLS.length, 1, "404 must not trigger a retry");
});
test("free gate 400 missing marketplaceId", async () => {
mockApi.install(() => mockApi.error(400, "Missing required parameter(s): marketplaceId"));
await assert.rejects(() => getWithRetry("amazon-product-lookup", { asin: ASIN }),
(err) => err instanceof ApiError && err.status === 400 && err.message.includes("marketplaceId"));
});
test("401 insufficient credits is not retried", async () => {
mockApi.install(() => mockApi.error(401, "Insufficient user credits."));
await assert.rejects(() => getWithRetry("amazon-product-lookup", { asin: ASIN, marketplaceId: MP }),
(err) => err.status === 401);
assert.equal(mockApi.CALLS.length, 1);
});
test("429 concurrency cap is free and retried", async () => {
let calls = 0;
mockApi.install(() => {
calls++;
return calls === 1 ? mockApi.error(429, "Max 40 concurrent requests per API key.", { "Retry-After": "2" })
: mockApi.ok(product());
});
const start = Date.now();
const out = await getWithRetry("amazon-product-lookup", { asin: ASIN, marketplaceId: MP });
assert.equal(out.productInfo.asin, ASIN);
assert.equal(mockApi.CALLS.length, 2);
assert.ok(Date.now() - start >= 2000, "must honour Retry-After, not a shorter backoff");
});
test("500 is refunded and retried exactly once", async () => {
mockApi.install(() => mockApi.error(500, "Internal error."));
await assert.rejects(() => getWithRetry("amazon-product-lookup", { asin: ASIN, marketplaceId: MP }),
(err) => err.status === 500);
assert.equal(mockApi.CALLS.length, 2, "exactly one retry after a 500, then stop");
});
test("502 is billed and retried up to the attempt cap", async () => {
mockApi.install(() => mockApi.error(502, "Upstream error."));
await assert.rejects(() => getWithRetry("amazon-product-lookup", { asin: ASIN, marketplaceId: MP }, 3),
(err) => err.status === 502);
assert.equal(mockApi.CALLS.length, 3, "502 is billed on every attempt, so the cap must be respected");
});
test("mock fails closed without install", async () => {
await assert.rejects(() => fetch("https://sellermagnet-api.com/api/amazon-product-lookup?api_key=x"),
/install/);
});
node --test --test-reporter=spec output (unmodified run)
✔ happy path parses the real response shape (12.923832ms)
✔ no featured offer price ("N/A") is not a number (2.093605ms)
✔ 404 is billed and must not be retried (3.731309ms)
✔ free gate 400 missing marketplaceId (2.303306ms)
✔ 401 insufficient credits is not retried (2.827907ms)
✔ 429 concurrency cap is free and retried (2007.360263ms)
✔ 500 is refunded and retried exactly once (2011.572476ms)
✔ 502 is billed and retried up to the attempt cap (6003.178858ms)
✔ mock fails closed without install (3.188302ms)
ℹ tests 9
ℹ suites 0
ℹ pass 9
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 10327.314842
Never hand-write a mock of sellermagnet.mjs itself
A mock that reimplements lookup() or getWithRetry() tests the mock's own logic, not the real client. Fake fetch, one level below your code, so a real bug in the parsing or retry logic still shows up as a failing test.
Does the same pattern work for other HTTP clients or runtimes?
Yes - fake the one function the real code calls to reach the network, whatever that function is. If a project uses axios or undici directly instead of the built-in fetch, replace that library's request function the same way this guide replaces global.fetch. 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 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 client code under test while the API itself never sees a request.
What exactly should I fake: my own client module, or fetch itself?
The global fetch function, never your own sellermagnet.mjs or retry.mjs. A hand-written mock of your own module can drift from the real one and still pass; faking only fetch means the exact parsing, retry and error code under test is the code that ships.
How do I simulate a 429 concurrency cap without waiting 20 seconds in every test run?
This suite does not fake setTimeout, so the 429 and 500 retry tests really wait out the Retry-After and backoff, the same way the Go mock-testing guide's tests really wait. If a faster suite matters more, wrap retry.mjs's sleep() so a test can replace it with a no-op and assert on the duration it was called with instead.
Does a fake fetch also test the credit math?
Yes, if the fake records every call it receives. Counting mockApi.CALLS.length after a 429 or a refunded 500 verifies the exact number of billed attempts a scenario produces, which is the same number a real burst would be charged.
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 global.fetch (or your language's equivalent one layer below the HTTP call), run the real 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 with zero npm installs and spends zero credits.