Testing your code
The testing kit lives in its own entry point, @kkkermit/trading212.js/testing, so it never ends up in your
production bundle. It works with any test runner; the examples use Node’s built-in one, so they need nothing installed, and
Vitest or Jest work the same way with their own describe, it and assertions.
The fake Trading 212
Section titled “The fake Trading 212”createFakeTrading212() returns a real Trading212 client whose fetch is an in-memory Trading 212, so your code
runs exactly as it would against the API: validation, errors, pagination, the live-trading switch and all. There is no
network and no key, and rate limiting is off, so tests run instantly.
import assert from "node:assert/strict";import { describe, it } from "node:test";
import { OrderRejectedError, type Trading212 } from "@kkkermit/trading212.js";import { createFakeTrading212 } from "@kkkermit/trading212.js/testing";
// The code under test: sells a holding once it is up 10%.async function takeProfit(t212: Trading212, ticker: string): Promise<boolean> { const position = await t212.positions.get(ticker); if (!position?.averagePricePaid || !position.currentPrice) return false; if (position.currentPrice < position.averagePricePaid * 1.1) return false; await t212.orders.sellAll(ticker); return true;}
describe("takeProfit", () => { it("sells once the price is up 10%", async () => { const { client, server } = createFakeTrading212({ state: { positions: [{ ticker: "AAPL_US_EQ", quantity: 3, averagePrice: 100 }] }, }); server.setPrice("AAPL_US_EQ", 105); assert.equal(await takeProfit(client, "AAPL_US_EQ"), false);
server.setPrice("AAPL_US_EQ", 111); assert.equal(await takeProfit(client, "AAPL_US_EQ"), true); assert.equal(server.position("AAPL_US_EQ"), undefined); });
it("passes on a refusal from Trading 212", async () => { const { client, server } = createFakeTrading212({ state: { positions: [{ ticker: "AAPL_US_EQ", quantity: 1, averagePrice: 100 }] }, }); server.setPrice("AAPL_US_EQ", 200); server.marketOpen = false; await assert.rejects(takeProfit(client, "AAPL_US_EQ"), OrderRejectedError); });});const assert = require("node:assert/strict");const { describe, it } = require("node:test");
const { OrderRejectedError } = require("@kkkermit/trading212.js");const { createFakeTrading212 } = require("@kkkermit/trading212.js/testing");
// The code under test: sells a holding once it is up 10%.async function takeProfit(t212, ticker) { const position = await t212.positions.get(ticker); if (!position?.averagePricePaid || !position.currentPrice) return false; if (position.currentPrice < position.averagePricePaid * 1.1) return false; await t212.orders.sellAll(ticker); return true;}
describe("takeProfit", () => { it("sells once the price is up 10%", async () => { const { client, server } = createFakeTrading212({ state: { positions: [{ ticker: "AAPL_US_EQ", quantity: 3, averagePrice: 100 }] }, }); server.setPrice("AAPL_US_EQ", 105); assert.equal(await takeProfit(client, "AAPL_US_EQ"), false);
server.setPrice("AAPL_US_EQ", 111); assert.equal(await takeProfit(client, "AAPL_US_EQ"), true); assert.equal(server.position("AAPL_US_EQ"), undefined); });
it("passes on a refusal from Trading 212", async () => { const { client, server } = createFakeTrading212({ state: { positions: [{ ticker: "AAPL_US_EQ", quantity: 1, averagePrice: 100 }] }, }); server.setPrice("AAPL_US_EQ", 200); server.marketOpen = false; await assert.rejects(takeProfit(client, "AAPL_US_EQ"), OrderRejectedError); });});Run it with node --test take-profit.test.cjs, or npx tsx --test take-profit.test.mts.
What it does:
- Market orders fill at once at the current price, moving cash and positions and writing history.
- Limit and stop orders wait until you call
server.fill(orderId, price?). Their cash or shares are reserved meanwhile. - It refuses what Trading 212 refuses: not enough cash, selling more than is available, more than 4 decimal
places, more than the instrument’s
maxOpenQuantity, an order worth less thanminOrderValue(1 by default),extendedHourson a non-market order, an unknown ticker, a closed market (server.marketOpen = false) and the wrong key. - History is paginated with
nextPagePath, like the real API. - CSV exports are refused on demo. Use
environment: "live"orserver.exportsOnDemo = trueto test them. It checks that your code sends no credentials to the download link.
Setting up the account
Section titled “Setting up the account”Everything in state is optional:
const { client, server } = createFakeTrading212({ state: { cash: 5000, currency: "GBP", prices: { AAPL_US_EQ: 200 }, positions: [{ ticker: "MSFT_US_EQ", quantity: 3, averagePrice: 380, inPies: 1 }], dividends: [{ ticker: "MSFT_US_EQ", amount: 2.1, paidOn: "2026-06-12T00:00:00Z" }], }, client: { logger: console }, // any other client option});Without instruments, it offers Apple, Microsoft and Tesla on US markets, and Vanguard’s S&P 500 ETF in London
(DEFAULT_INSTRUMENTS). A ticker without a price costs 100.
Changing it during a test
Section titled “Changing it during a test”server.setPrice("AAPL_US_EQ", 250);server.marketOpen = false; // every order is refused with market-closedserver.failNext("placeMarketOrder", { status: 400, body: { type: "/api-errors/min-quantity-exceeded", detail: "must trade at least 2" },});server.failNext("getAccountSummary", { network: "ECONNRESET" });
server.position("AAPL_US_EQ"); // the position as the API would return it, or undefinedserver.cash; // free cashserver.requests; // every request the client made, without credentialsfailNext() takes the endpoint’s name from ENDPOINTS and
either a response or { network: code }; queue several to fail several calls. Every control is listed in the
testing kit reference.
Testing the live switch
Section titled “Testing the live switch”A live fake has trading enabled unless you say otherwise, so you can test what happens when it is off:
const { client } = createFakeTrading212({ environment: "live", client: { trading: "disabled" } });await expect(client.orders.buy(order)).rejects.toBeInstanceOf(TradingDisabledError);Scripted fetch
Section titled “Scripted fetch”For testing at the HTTP level, scriptedFetch() answers from a list, in order, and records every request:
import { Trading212 } from "@kkkermit/trading212.js";import { networkError, scriptedFetch } from "@kkkermit/trading212.js/testing";
// Each request takes the next step: a response, a function of the request, or a network failure.const { fetch, requests, pending } = scriptedFetch([ { status: 503 }, { body: { id: 1, currency: "GBP", totalValue: 100 }, headers: { "x-ratelimit-remaining": "0" }, }, (request) => ({ body: { echoed: request.query } }), networkError("ECONNREFUSED"),]);
const t212 = new Trading212({ environment: "demo", apiKey: "test-key", apiSecret: "test-secret", fetch, rateLimit: "off", retry: { baseDelayMs: 1 },});
const summary = await t212.account.summary(); // retried after the 503console.log(summary.totalValue); // 100console.log(requests.length, pending()); // 2 requests made, 2 steps leftconsole.log(requests[0]?.authorized); // true, and the credentials themselves are never recordedconst { Trading212 } = require("@kkkermit/trading212.js");const { networkError, scriptedFetch } = require("@kkkermit/trading212.js/testing");
async function main() { // Each request takes the next step: a response, a function of the request, or a network failure. const { fetch, requests, pending } = scriptedFetch([ { status: 503 }, { body: { id: 1, currency: "GBP", totalValue: 100 }, headers: { "x-ratelimit-remaining": "0" }, }, (request) => ({ body: { echoed: request.query } }), networkError("ECONNREFUSED"), ]);
const t212 = new Trading212({ environment: "demo", apiKey: "test-key", apiSecret: "test-secret", fetch, rateLimit: "off", retry: { baseDelayMs: 1 }, });
const summary = await t212.account.summary(); // retried after the 503 console.log(summary.totalValue); // 100 console.log(requests.length, pending()); // 2 requests made, 2 steps left console.log(requests[0]?.authorized);}
main().catch((error) => { console.error(error); process.exitCode = 1;});A step is a response ({ status, body, headers }, all optional), a function that receives the request and returns
one, or an error to throw as a network failure, such as networkError("ECONNREFUSED"). pending() says how many
steps are left.
Contract tests against demo
Section titled “Contract tests against demo”This repository’s own tests/contract suite runs against the real demo API with npm run test:demo when
T212_DEMO_API_KEY and T212_DEMO_API_SECRET are set, in the shell or in .env. It never touches live.