Back to BlogQuality & Testing

Test My Node/Express API: Contract, Auth and Data Tests

Rupak Amin

Founder & Lead Engineer, RAITHub

7 min read

RAITHub ships and tests production software. See QA as a Service or talk to us.

Testing a Node/Express API means exercising each endpoint over HTTP against a real test database: status code, response schema, who is allowed to call it, the business rules, idempotency and error handling. Unit-test the pure logic beneath, and add contract tests only when another team's app depends on your API. RAITHub does this as a plan, an audit or a managed team.

If you would rather have the suite built and run for you, see how RAITHub would test this near the end.

What should you test on a Node/Express API?

An API's bugs are rarely in the happy path. They are in the cases teams skip under deadline: bad input, missing tokens, one user reaching another's records, a payment charged twice. Test each endpoint for all of them. The OWASP API Security Top 10 2023 puts broken object level authorisation first (OWASP API Security Top 10 2023): one user changing an ID to read someone else's data. Only an API test proves the server refuses.

CheckExampleWhy it matters
Happy pathPOST /orders with valid data returns 201 and the new orderThe basic promise of the endpoint
ValidationMissing or wrong-type input returns 400 or 422, never 500A 500 on bad input means unchecked data reached the database
AuthenticationNo token, expired token and malformed token all return 401Protected data must never reach anonymous callers
AuthorisationUser B asking for user A's order returns 403 or 404; a viewer cannot deleteThe commonest serious API flaw
Business rulesCannot refund more than was paid; stock cannot go negativeWhere money and data go wrong
IdempotencyRepeating a request with the same key creates one recordNetworks retry; clients double-submit
Errors and limitsRate limits return 429 with Retry-After; pagination behavesPredictable failure keeps clients stable

For the full endpoint checklist and idempotency detail, see the API testing guide.

What does a good Express integration test look like?

Run the real Express app against a disposable test database and drive it over HTTP. Supertest is the standard way to do this in Node: it starts your app in-process and sends requests to it (Supertest). This test, with the Node built-in test runner (node:test), checks the happy path and the authorisation rule that matters most:

// test/orders.test.js
import { test } from 'node:test'
import assert from 'node:assert/strict'
import request from 'supertest'
import { app } from '../src/app.js'

test('a user cannot read another order', async () => {
  const created = await request(app)
    .post('/api/orders')
    .set('Authorization', 'Bearer ' + process.env.ALICE_TOKEN)
    .send({ sku: 'TEST-1', qty: 1 })
  assert.equal(created.status, 201)

  const res = await request(app)
    .get('/api/orders/' + created.body.id)
    .set('Authorization', 'Bearer ' + process.env.BOB_TOKEN)
  assert.ok([403, 404].includes(res.status))
})

Write that second kind of test for every resource and role. It is dull, and it is the test that stops the data leak. Each test creates its own data with unique IDs so tests do not depend on each other's leftovers.

Free checklist

AI-Built App Launch Readiness Checklist

25 checks before you let real users in. Enter your email and we’ll reveal it below (and send you a copy).

One email, the checklist, no spam. By submitting you agree we can email you this checklist and reply to your enquiry.

Should you mock the database, or hit a real one?

Hit a real one: a disposable test database or a container that resets between runs. Mocking the database hides exactly the bugs API tests exist to catch, like a query that returns the wrong rows or a constraint that is not enforced. Stub only the slow or external third parties at the boundary, payments, email and SMS, and test those separately in sandbox mode. Payment callbacks have their own traps; see testing payments and webhooks.

DependencyIn the test
Your databaseReal, disposable, reset per run
Payment providerStubbed at the boundary; tested separately in sandbox
Email / SMSStubbed; assert it was called once with the right data
Another team's serviceStubbed, plus a contract test where deploys are independent

Do you need contract tests?

You need them when a mobile app, a partner, or another team's service calls your API and deploys on its own schedule. A contract test checks that both sides agree without running both together, so a change that would break a consumer fails your build first. You probably do not need them when one team ships the frontend and backend together from one repository: an ordinary integration test plus shared types catches the same breaks with less machinery. The API testing guide shows a minimal contract test.

Buy, build or hire?

OptionChoose this whenWatch out for
A tool or SaaS testing platformYou want API monitors and collections with little codeTests that live outside your repository and drift from the code
Freelancers or crowdtestingYou need a one-off pass on a small APINo one maintains the suite afterwards
An in-house QA hireYou have several services and release weeklyNeeds an engineer who codes, not only a manual tester
A managed QAaaS teamYou want the suite built, wired into CI and kept current monthlyMake sure the tests live in your repository and you own them

Why RAITHub for testing a Node/Express API?

Because Node and TypeScript are RAITHub's own stack: the engineers who write the tests also build Node APIs, so they test authorisation, idempotency and error handling the way these fail in production. TheSkinProof, the founder's own venture, has 217 API endpoints and 750+ tests; Sundor Skin, a B2B wholesale platform, has 530+ tests and 88 permission codes across 12 staff roles, the kind of matrix where authorisation tests earn their keep. How that discipline works is in QA-first development: how RAITHub tests.

When you don't need RAITHub: if you want an engineer placed inside your team under your management, that is staff augmentation, which RAITHub does not offer. If the API itself needs building or rescuing, see API and backend development. For attack-focused testing of the same endpoints, see security testing; that is application-level testing against OWASP guidance, not a certified penetration test.

How RAITHub would test this

Through QA and test automation, part of QA as a service, RAITHub would:

  • map endpoints, roles and the money and data paths from your spec or the code
  • write integration tests over HTTP against a real test database for the happy path, validation, authentication, an authorisation matrix per role, idempotency and errors
  • add contract tests where independent consumers justify them, and stub third parties at the boundary
  • wire the suite into your CI so a failing change blocks the release, with tests and configuration in your repository

Buy it as a monthly QA plan, a fixed-price one-off audit, or a dedicated QA team that RAITHub manages and bills monthly. Testers are never placed under your management. You own the tests and the IP, and an NDA is signed first. Start with a free 15-minute call, then a written fixed quote. Talk to RAITHub about testing your API.

Frequently asked questions

How do I test a Node/Express API?

Run the real app against a disposable test database and drive each endpoint over HTTP with Supertest or a similar tool, checking status, schema, authentication, authorisation per role, business rules, idempotency and errors, all in CI on every change.

Should I mock the database in API tests?

No. Use a real disposable test database so the tests catch wrong queries and unenforced constraints. Mock only slow external services like payments and email at the boundary, and test those separately in sandbox mode.

What is the difference between integration and contract testing?

Integration testing checks that your endpoint behaves correctly end to end. Contract testing checks that a consumer and your API agree on requests and responses, so each can deploy independently without breaking the other.

How many API tests do I need?

At least one happy-path, one validation and one authorisation test per endpoint and role, plus a test for every business rule that moves money or data. Count risks covered, not tests.

Can RAITHub test an API it did not build?

Yes. RAITHub starts with the endpoints that cost most when they break, writes tests that pin down current behaviour, and gates them in CI before widening coverage or changing any code.

Does RAITHub do API security testing?

Yes, as application-level testing against OWASP guidance, including authorisation tests per role. It is not a CREST- or PCI-certified penetration test and produces no compliance attestation.

node testingexpress testingapi testingintegration testingcontract testingQA as a service

Ready to discuss your project?

Book a free 15-minute technical audit with our engineering team.