Mock IBAN validation is two different jobs that often get mixed up. The first is testing your own validator: length, characters, MOD-97, the things you can compute offline. There you should not mock anything; you need good inputs, and plenty of them. The second is testing the code that calls someone else, a bank-account verification API, a payment provider's sandbox or a payee-verification service. There you must mock, because the real thing is slow, rate-limited, costs money or does not exist in CI.
This post walks through both halves with working examples: unit tests with generated IBANs, property-based tests in JavaScript and Python, contract-style mocks for an external verification API, browser tests that fill an IBAN field, and ways to pull fresh test IBANs from our public MCP server or API inside your tooling. Every snippet below was run before publication, except the Cypress one, which follows the documented API but was not executed.
Where test IBANs come from
Before any mocking, settle the data question. A hand-typed IBAN almost never has correct check digits, and a real customer's IBAN has no place in a test suite. You have three sound sources:
- The registry examples. Every country in the SWIFT IBAN Registry comes with one example IBAN, such as
DE89370400440532013000. They are public, stable and valid, and most libraries use them in their own tests. The drawback: there is exactly one per country, so a validator that special-cases it would pass. - Generated IBANs. Our generator builds structurally valid IBANs for 91 countries, with the correct national check digits for the 27 countries that have them, and in realistic mode (the default) a real bank code from the 84 countries with a verified list. Download up to 100 at a time as CSV, JSON, SQL or plain text from the "Generate a list" option, or fetch them from a script (see below). They were not issued by any bank. Never use them for payments.
- Your own check-digit helper. For property-based tests you want thousands of distinct valid IBANs per run, so compute the check digits locally from a random BBAN. The helper is six lines, and it doubles as an oracle: if your validator rejects an IBAN the helper produced, one of them is wrong.
The IBANpedia article https://generaterandomiban.com/en/ibanpedia/test-ibans goes into what a validator can and cannot check against a random IBAN. The short version: structure yes, existence no.
Unit tests for your own validator
Start with a fixed table: the registry example per country you support, each one with a single digit changed, the example lowercased and spaced, an empty string, a string of 40 characters, a country you do not support. Table-driven tests are boring and that is their virtue; they document the behaviour. https://generaterandomiban.com/en/blog/how-to-test-iban-validation has a full checklist of cases, and the MOD-97 implementation itself is covered in https://generaterandomiban.com/en/blog/validate-iban-javascript and https://generaterandomiban.com/en/blog/iban-validation-python-php-java.
What a table cannot give you is coverage of the input space. For that, add property-based tests.
Property-based tests with fast-check
A property-based test states a rule that must hold for every input and lets a library generate the inputs, shrinking any failure to a minimal case. The example uses fast-check with Node's built-in test runner and our open-source validator iban-check as the code under test. Replace isValidIBAN with your own function.
// iban.test.mjs (run with: node --test)
import { test } from 'node:test';
import assert from 'node:assert/strict';
import fc from 'fast-check';
import { validateIBAN, isValidIBAN } from 'iban-check';
// ISO 7064 MOD 97-10: compute the two check digits for a country code and a BBAN.
function withCheckDigits(country, bban) {
const numeric = (bban + country + '00').replace(/[A-Z]/g, (c) => String(c.charCodeAt(0) - 55));
let remainder = 0;
for (const digit of numeric) remainder = (remainder * 10 + Number(digit)) % 97;
return country + String(98 - remainder).padStart(2, '0') + bban;
}
// Arbitrary: a well-formed German IBAN (8-digit bank code + 10-digit account).
const germanIban = fc.stringMatching(/^[0-9]{18}$/).map((bban) => withCheckDigits('DE', bban));
test('every well-formed German IBAN passes validation', () => {
fc.assert(fc.property(germanIban, (iban) => isValidIBAN(iban)));
});
test('a single wrong digit is always reported as a checksum error', () => {
fc.assert(
fc.property(germanIban, fc.integer({ min: 4, max: 21 }), fc.integer({ min: 1, max: 9 }), (iban, pos, delta) => {
const digit = (Number(iban[pos]) + delta) % 10;
const tampered = iban.slice(0, pos) + digit + iban.slice(pos + 1);
assert.equal(validateIBAN(tampered).error, 'INVALID_CHECKSUM');
}),
);
});
test('whitespace and lowercase never change the verdict', () => {
const noise = fc.constantFrom(' ', ' ', '\t', '');
fc.assert(
fc.property(germanIban, noise, fc.boolean(), (iban, sep, lower) => {
let typed = iban.match(/.{1,4}/g).join(sep);
if (lower) typed = typed.toLowerCase();
assert.equal(validateIBAN(typed).normalized, iban);
assert.equal(validateIBAN(typed).valid, true);
}),
);
});
The second property relies on a real guarantee of the MOD 97-10 scheme: it detects every single-character substitution. The third one encodes a rule from real life, where users paste IBANs with non-breaking spaces from PDFs. fc.stringMatching builds strings from a regular expression, fc.constantFrom picks one of a fixed set, and fc.assert runs 100 cases by default ({ numRuns: 1000 } as a second argument raises it).
The same idea in Python with Hypothesis
Hypothesis is the Python equivalent. st.from_regex(..., fullmatch=True) plays the role of fc.stringMatching. This example targets Dutch IBANs, whose BBAN starts with four letters, so it also covers the letter-to-number conversion. Save it as test_iban.py and run pytest.
import re
from hypothesis import given, strategies as st
def mod97(s: str) -> int:
numeric = "".join(str(int(c, 36)) for c in s) # A=10 ... Z=35
remainder = 0
for ch in numeric:
remainder = (remainder * 10 + int(ch)) % 97
return remainder
def iban_valid(iban: str) -> bool:
iban = re.sub(r"\s+", "", iban).upper()
if not re.fullmatch(r"[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}", iban):
return False
return mod97(iban[4:] + iban[:4]) == 1
def with_check_digits(country: str, bban: str) -> str:
check = 98 - mod97(bban + country + "00")
return f"{country}{check:02d}{bban}"
dutch_bbans = st.from_regex(r"[A-Z]{4}[0-9]{10}", fullmatch=True) # 4-letter bank code + 10-digit account
@given(dutch_bbans)
def test_generated_dutch_ibans_validate(bban):
assert iban_valid(with_check_digits("NL", bban))
@given(dutch_bbans, st.integers(min_value=8, max_value=17), st.integers(min_value=1, max_value=9))
def test_single_digit_errors_are_caught(bban, pos, delta):
iban = with_check_digits("NL", bban)
digit = (int(iban[pos]) + delta) % 10
tampered = iban[:pos] + str(digit) + iban[pos + 1:]
assert not iban_valid(tampered)
@given(st.text(min_size=1, max_size=40))
def test_garbage_never_raises(text):
assert iban_valid(text) in (True, False)
The last test is the one that finds real bugs: arbitrary Unicode input must produce a boolean, not an exception. iban_valid here is deliberately minimal (no per-country length table); a production validator should check the length for the country, as described in https://generaterandomiban.com/en/ibanpedia/iban-formats-by-country.
Mocking an external bank-account verification API
Once the IBAN passes your own checks, many systems call a third party: a service that confirms the account exists, matches the holder's name, or checks the IBAN against a sanctions list. In the euro area this is now the territory of Verification of Payee, which the payer's bank performs before a credit transfer. You cannot call those services from a unit test, and you should not call a sandbox on every CI run either.
The usual pattern is a request-level mock: intercept the HTTP call and answer with the exact responses the provider documents. In JavaScript, Mock Service Worker (MSW) does this in Node and in the browser with the same handlers.
// verify.test.mjs (run with: node --test)
import { test, before, after, afterEach } from 'node:test';
import assert from 'node:assert/strict';
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
// The code under test: a thin client for an external account-verification API.
async function verifyAccount(iban, name) {
const res = await fetch('https://verify.example.com/v1/accounts/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ iban: iban.replace(/\s+/g, '').toUpperCase(), name }),
});
if (res.status === 404) return { status: 'unknown_account' };
if (!res.ok) throw new Error(`verification failed: ${res.status}`);
return res.json();
}
// The mock: one handler per response the real API documents.
const server = setupServer(
http.post('https://verify.example.com/v1/accounts/verify', async ({ request }) => {
const { iban } = await request.json();
if (iban === 'DE89370400440532013000') return HttpResponse.json({ status: 'match' });
if (iban === 'DE79120300002058483629') return HttpResponse.json({ status: 'close_match', suggested_name: 'Erika Mustermann' });
return HttpResponse.json({ error: 'account_not_found' }, { status: 404 });
}),
);
before(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => server.resetHandlers());
after(() => server.close());
test('a matching account comes back as a match', async () => {
assert.deepEqual(await verifyAccount('DE89 3704 0044 0532 0130 00', 'Max Mustermann'), { status: 'match' });
});
test('an unknown account is reported, not thrown', async () => {
assert.deepEqual(await verifyAccount('DE56500400007476001280', 'Nobody'), { status: 'unknown_account' });
});
test('a 500 from the provider surfaces as an error', async () => {
server.use(http.post('https://verify.example.com/v1/accounts/verify', () => HttpResponse.text('boom', { status: 500 })));
await assert.rejects(verifyAccount('DE89370400440532013000', 'Max'), /verification failed: 500/);
});
Three habits make these mocks worth having:
- Map each documented outcome to a fixture IBAN: match, close match, no match, account closed, provider down. Pick a generated IBAN for each (the ones above come from our generator; the first is the registry example) and keep the mapping in one place, so a new team member can read what
DE79120300002058483629means in your suite. - Set
onUnhandledRequest: 'error'. A test that silently reaches the real provider is worse than a failing one. - Mirror the provider's sandbox. Payment providers usually publish "magic" test IBANs that trigger specific results in their sandbox. Use those values in your mocks too, so the mocked and the sandbox runs agree.
Mocks drift from the real API over time. Consumer-driven contract testing, with a tool such as Pact, turns the same request/response pairs into a contract the provider can verify on their side; if your provider offers that, the fixtures above become the examples in the contract. Otherwise, schedule a small nightly job against the sandbox so a changed field name shows up before a customer finds it.
Browser tests: filling the IBAN field
End-to-end tests should check the form, not the bank. Stub the network call behind the form and assert on what the user sees. In Playwright, page.route intercepts the request and route.fulfill answers it; locator.fill is the recommended way to enter text.
// e2e/iban-form.spec.mjs (run with: npx playwright test)
import { test, expect } from '@playwright/test';
test('shows the verification result for a pasted IBAN', async ({ page }) => {
// Stub the backend call: the e2e test checks the form, not the bank API.
await page.route('**/api/verify', async (route) => {
const { iban } = route.request().postDataJSON();
const status = iban.replace(/\s+/g, '') === 'DE89370400440532013000' ? 'match' : 'no_match';
await route.fulfill({ json: { status } });
});
await page.goto('https://app.example/payout');
await page.getByLabel('IBAN').fill('DE89 3704 0044 0532 0130 00');
await page.getByRole('button', { name: 'Save' }).click();
await expect(page.getByRole('status')).toHaveText('match');
});
Use fill for the normal case and pressSequentially only when the field formats as you type (auto-spacing every four characters, for instance), because that behaviour depends on individual key events. Test paste explicitly as well: real users paste de89 3704 0044 0532 0130 00 with a trailing line break more often than they type it.
The Cypress version uses cy.intercept with a static response and .type():
cy.intercept('POST', '**/api/verify', { statusCode: 200, body: { status: 'match' } }).as('verify');
cy.visit('/payout');
cy.get('input[name=iban]').type('DE89 3704 0044 0532 0130 00');
cy.contains('button', 'Save').click();
cy.wait('@verify').its('request.body.iban').should('eq', 'DE89 3704 0044 0532 0130 00');
cy.get('[role=status]').should('have.text', 'match');
Fresh test IBANs from the MCP server or the API
Fixtures committed to the repository are right for most suites. Sometimes you want variety, a new country, or a hundred rows for a load test, without hand-maintaining files. Two public endpoints help.
The MCP server at https://generaterandomiban.com/mcp speaks JSON-RPC 2.0 over plain HTTP, needs no key, and is limited to 120 requests a minute. Its generate_iban tool takes country, count (1 to 100) and realistic (default true). The result is an MCP tool result, so the data sits as a JSON string inside result.content[0].text:
// mcp-fixtures.test.mjs (run with: node --test)
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { isValidIBAN } from 'iban-check';
// Ask the public MCP server for test IBANs (no API key; 120 requests a minute).
async function testIbans(country, count = 5) {
const res = await fetch('https://generaterandomiban.com/mcp', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: { name: 'generate_iban', arguments: { country, count } },
}),
});
const { result, error } = await res.json();
if (error || result.isError) throw new Error(error?.message ?? result.content[0].text);
return JSON.parse(result.content[0].text).ibans.map((row) => row.iban);
}
test('fresh Belgian test IBANs pass the local validator', async () => {
const ibans = await testIbans('BE', 5);
assert.equal(ibans.length, 5);
for (const iban of ibans) assert.ok(isValidIBAN(iban), iban);
});
The same server exposes validate_iban (MOD-97, length and country support) and list_countries. AI coding assistants that speak MCP can use it directly; the discovery card is at /.well-known/mcp/server-card.json.
For a file rather than a call, the export URL behind "Generate a list" is a plain GET with no key, limited to 30 downloads a minute, and the REST API documented in the https://generaterandomiban.com/en/apis/docs returns the same data with an API key (free, requested by email):
curl -o belgium.json "https://generaterandomiban.com/export/be?format=json&count=100" # one object per IBAN, bank and account in separate fields
curl -H "X-API-Key: YOUR_KEY" "https://generaterandomiban.com/api/v1/generate/BE?count=100" # the same through the REST API
Two cautions. Tests that reach the network are integration tests: keep them out of the unit suite, give them a timeout, and cache the result when you can. And a generated IBAN is "not issued by any bank", which is exactly what you want in a fixture and exactly why it will fail any check that looks the account up.
Which test goes where
| Layer | What it checks | Test double | IBAN source |
|---|---|---|---|
| Validator unit tests | Characters, length, MOD-97, national check digits | None | Registry examples, generated fixtures |
| Property-based tests | Rules that hold for every input | None | Check-digit helper in the test |
| Verification client | Mapping of provider responses to your domain | HTTP mock (MSW, WireMock, responses) |
One fixture IBAN per documented outcome |
| Contract tests | Mock still matches the provider | Pact or a nightly sandbox run | The same fixtures |
| Browser tests | The form, paste, formatting, messages | page.route / cy.intercept |
A handful of fixtures |
| Load and data tests | Volume, uniqueness, encoding | None | Export or MCP, 100 per call |
A suite that only has the first row ships a validator that works and a payout flow that nobody has tested; a suite that only has the last two mocks away the one piece of logic you own.
Sources
- SWIFT IBAN Registry: country structures and example IBANs
- ISO 13616-1: IBAN structure and the ISO/IEC 7064 MOD 97-10 check digits
- fast-check documentation:
fc.property,fc.assert, arbitraries - Hypothesis strategies reference:
from_regex,integers,text - Mock Service Worker, quick start:
http,HttpResponse,setupServer - Pact documentation: consumer-driven contract testing
- Playwright, Mock APIs and Actions:
page.route,route.fulfill,locator.fill - Cypress, cy.intercept and .type()
- iban-check on npm: the open-source validator used in the examples
- Generate Random IBAN MCP server card and API documentation