Testing a Strapi API with Jest

A practical guide to running Jest and Supertest against an in-memory SQLite Strapi, covering authenticated requests and a CI gate before each deployment. It also shows what a team should confirm before relying on the suite.

On this page

Why teams test a Strapi API with Jest before each deployment

Custom routes, controllers and policies change how a Strapi API behaves, and editors and front ends depend on that behavior. A change to a controller that filters entries, a policy that checks ownership, or a route that returns a new field can break a page or expose data without any visible error during development. Teams that add custom endpoints or permission logic need a repeatable check that runs the same way every time, so a regression is caught before the build reaches production rather than after an editor reports it.

Jest is the test runner. It defines the test cases, runs them, and reports failures. Supertest sends HTTP requests to the Strapi application and checks the status codes, response bodies and headers that come back. Together they let the team assert what an authenticated editor, an anonymous visitor and a restricted role each receive from the same endpoint. For this setup, the database is an in-memory SQLite database. Strapi 5 supports SQLite 3, so the tests can start from a clean state on each run, though the team should confirm that the test database matches the production engine closely enough for the queries they rely on.

The test suite is a layer the project owns. It is not a Strapi feature, and Strapi does not ship it or maintain its contents. Teams usually need it in three situations: when they add custom endpoints that core routes do not cover, when they change who can read or write content, and when they want a pre-deployment gate in CI that blocks a release on failing tests. Before committing to this approach, confirm which Strapi version and Node.js version the project targets against the current Strapi installation requirements, and agree who owns the test data and fixtures.

How a test request moves from Jest to the database and back

The run starts in the Jest test runner, which calls Supertest to send an HTTP request to a Strapi instance started in test mode. Strapi routes the request through its policies and controllers, which read and write an in-memory SQLite database that exists only for the life of the test process. The response returns to the assertion in the test, and the CI job fails the build if any assertion fails. Check that the test database and any shared staging environment stay on opposite sides of the boundary, so test data never reaches a shared system.

Test requests stay inside the CI job, isolated from shared data.

Which test setup fits which Strapi project

This table compares the test database, test style and data strategies you can combine for a Strapi API suite. Read each row as a choice you make for one part of the suite, then check the 'what it misses' column before you decide what still needs a second layer of testing. The main takeaway is that fast in-memory SQLite suits most API logic checks, while database-specific behavior needs a containerized database run in CI.

ChoiceWhen it fitsWhat it catchesWhat it misses
In-memory SQLite test databaseEarly and frequent runs on a project whose production database is also SQLite or whose queries are simpleRoute wiring, controller logic, policy decisions, response shape and most Document Service behaviorDifferences in SQL dialect, collation, JSON handling and migration behavior that appear on PostgreSQL or MySQL
Containerized PostgreSQL or MySQL test databaseProjects that run PostgreSQL, MySQL or MariaDB in production and need the same engine in testsEngine-specific query behavior, unique constraint errors, transaction semantics and migrations against the target schemaProduction-scale data volume, network latency between app and database, and managed database settings such as failover
Unit tests of servicesPure business logic in custom services, such as pricing, eligibility or status rulesLogic errors in functions that can be called without an HTTP request, and fast feedback on edge casesRouting, authentication, permissions, sanitization and serialization, which only a request exercises
Full HTTP tests with SupertestCustom endpoints, policies and any rule that depends on who is calling the APIThe complete path from request to response, including status codes, authenticated roles and public permission settingsInternal branches that a single endpoint does not reach, and slow paths that need many calls to trigger
Seeded fixturesStable reference data such as roles, categories and a small set of known editors and articlesPredictable assertions with readable expected values, and repeatable failures that are easy to reproduceSchema changes that make old fixtures invalid until someone updates them, and data shapes the fixture author did not think of
Factory-generated dataSuites where many records with varied fields are needed, such as list filtering, pagination or bulk importsEdge cases in filters and pagination, and gaps in required fields or relations that hand-written fixtures skipSpecific production data quirks, and random values can hide flaky ordering unless the test sets its own sort order
Cleanup between testsAny suite where tests write data and later tests read itLeaked state that makes one test pass only when another runs firstNothing by itself; cleanup adds run time, so check the cost in CI before you tune it
Confirm in your environmentBefore you choose a database for CI, confirm the Strapi version, Node.js version and database versions your project supportsMismatches between the test engine and the production engine that would otherwise surface only at deployVersion support changes over time, so check the current Strapi installation requirements and your own pinned images

Setting up Jest and Supertest in a Strapi project

This sequence takes a Strapi project from a clean Node.js install to a passing Jest and Supertest suite that boots Strapi against an in-memory SQLite database. Each step closes with a check, so the team knows the foundation works before writing business tests.

  1. Confirm Node.js version against Strapi requirements

    The developer checks the Node.js version on their machine and on the CI runner, then confirms it is an Active or Maintenance LTS release, which Strapi 5 requires. Use node --version in the project directory and compare the result with the Node.js release schedule and the version named in the Strapi installation requirements. Align the local and CI versions now, because a mismatch often causes failures that look like test bugs. The step is done when both environments report the same supported major version.

  2. Install Jest and Supertest as dev dependencies

    The developer adds Jest, Supertest and a Strapi-compatible test runner setup to the project as development dependencies, keeping them out of the production build. Run the install command from the project root and commit the updated package.json and lockfile so every machine resolves the same versions. Confirm the packages you choose are compatible with the TypeScript or JavaScript setup in the project, and check the Strapi documentation for any testing guidance that names specific packages. The step is done when npx jest --version and npx supertest --help both run without errors.

  3. Create a test environment file pointing to SQLite

    The developer creates a separate environment file for tests, such as .env.test, and sets the database client to SQLite with a file path that is either in memory or in a temporary location that is deleted after each run. Keep secrets such as APP_KEYS, API_TOKEN_SALT and JWT_SECRET in this file with test-only values, and never reuse production secrets. Load the file only when the test command runs, so the development and production databases are never touched. The step is done when the test configuration reads the SQLite settings and the file is excluded from version control.

  4. Boot Strapi once per test suite

    The developer writes a shared setup helper that starts the Strapi application once before the suite runs and stops it after the last test finishes. Booting Strapi for every test is slow and can leave database connections open, so one instance per suite is the common pattern. The helper also exposes the Strapi instance and a Supertest agent for the tests to use. Verify that the helper runs the bootstrap and destroy calls in the right order. The step is done when a trivial test can read the Strapi instance and the process exits cleanly after the run.

  5. Write the first request test

    The developer writes a test that sends a public request to a content endpoint or the root route through Supertest and asserts on the status code and response shape. Keep the first test small and read-only, because it proves the wiring between Jest, Supertest and the running Strapi instance. If the endpoint is not public, the test should expect the correct denial status rather than a success. Check the response format against the Strapi version in use, since the response shape changed between Strapi 4 and Strapi 5. The step is done when the test asserts on a real response from the running application.

  6. Run the suite locally and confirm it passes

    The developer runs the test command from the project root and checks that Jest starts, boots Strapi on the SQLite test database, runs the request test and exits with code zero. Confirm the test database file is created and removed as expected, and that the development database is unchanged. Run the suite twice in a row to catch leftover state or port conflicts. The step is done when two consecutive local runs pass and the output shows the Strapi instance started and stopped without warnings that point to unclosed handles.

Testing authenticated requests and permissions

The core of this section is proving that Strapi enforces who can do what, and that the suite fails when it stops doing so. Each test should run as a known identity: an unauthenticated request, a request from an authenticated user with the default role, and a request from a user with a role you have customized. Create these users through the Users & Permissions plugin in the test setup, not by hand in an admin panel, so the suite can rebuild them on every run. Use Supertest to call the /api/auth/local endpoint with an identifier and password, read the jwt field from the response, and send it as a Bearer header on later requests. Confirm the exact login response shape for your Strapi version in the official documentation before you hard-code field names.

Public permissions deserve their own assertions. Send a request to each content endpoint with no token and check that only the routes you intend to expose return data, and that writes return an authorization error. Then repeat the same request as an authenticated user with the default role and compare the results. For ownership rules, create two users, have the first create an entry through your custom route, and confirm the second user receives a forbidden response when updating or deleting it. Policies that read the user from context are where these bugs usually hide, so test both the allowed and denied paths for each policy.

Test credentials should never be real. Generate passwords at runtime or read them from environment variables set only in CI, and create throwaway accounts in the isolated SQLite database that the suite destroys at the end of the run. Do not commit passwords, tokens or copies of a production .env file to the repository, and do not point the suite at a staging identity provider. Confirm with your security team how CI secrets are stored and who can read job logs, because a failing assertion can print a token. Keep this policy in writing so reviewers can check it during a security review.

Running the suite in CI before each deployment

The pull request check is the fastest gate and the one developers see most often. It runs on every proposed change before merge and should exercise the full Jest and Supertest suite against the in-memory SQLite database, so that route, policy and validation changes are tested in isolation. Because it runs on untrusted branches from contributors, it should never receive production credentials or access to real identity providers.

  • Trigger: run on every pull request and on pushes to open branches, with the job blocking merge through a required status check.
  • Database: start Strapi against SQLite in memory so each run begins from a clean schema with no shared state.
  • Environment: load only test values for secrets such as the admin JWT and API token salts, generated per run or stored as CI-only test values.
  • Cache: cache node_modules keyed to the lockfile so installs stay short without sharing build artifacts across branches.
  • Output: publish the JUnit or coverage report as a build artifact so reviewers can see which tests failed.

Check that the required status check is enforced on the protected branch, not only displayed, and that forked pull requests cannot read repository secrets.

Keeping test data and credentials out of the wrong places

A Strapi test suite touches real tokens, seeded records and CI credentials, so each of those can leak into places it should never reach. The cards below cover the controls that keep test material contained, from log output to the runner that executes the suite.

Scrub tokens from test logs

Supertest output, failed assertion messages and Jest snapshots can print the Authorization header or the JWT returned by /auth/local. Configure the test helpers so they never log full request headers or response bodies that contain tokens, and avoid console.log of login responses. Before merging, search CI logs from a failed run for the Bearer prefix to confirm nothing was printed. Treat any token that did appear as compromised and rotate it.

Seed only synthetic personal data

Fixtures copied from production users, support tickets or form submissions put real personal information into test databases, CI caches and artifacts. Generate test users with obviously fake names, reserved example email domains and random identifiers, and never restore a production dump into the test environment. Ask whoever owns data protection in your organization to confirm which fixture sources are allowed. Keep the seed script in version control so reviewers can see exactly what is inserted.

Keep test configuration out of builds

Test-only settings such as relaxed permissions, a fixed APP_KEYS value, or a seeded admin account can slip into a production image if the build copies the whole project. Put test config in files that the production build excludes, and set test values only through environment variables that the test runner injects. Check the built image or artifact for test-only files before each deployment. Confirm that the production .env never references the in-memory SQLite database used by the suite.

Use dedicated test credentials

Test accounts should be separate from editor and administrator accounts, and they should hold only the roles the test case needs. Create a dedicated Strapi user for each role under test, store its password in the CI secret store, and rotate it on a schedule your team sets. Never reuse a super administrator login for API tests. Remove the test accounts from any environment where they are no longer needed.

Limit what the CI runner can reach

A CI runner that runs the Strapi suite rarely needs access to production databases, cloud accounts or deployment keys. Give the test job its own runner pool, a short-lived token, and no network route to live systems. Restrict which branches can read secrets, and keep deployment credentials in a separate job that runs only after the tests pass. Ask your platform team to confirm which secrets the test job can read.

How much effort does a Strapi test suite take to build?

What is the main driver of effort for a Strapi test suite?

The main driver is how much custom behavior the suite has to cover. Each custom route, controller, policy and Users & Permissions rule adds cases for allowed roles, denied roles, unauthenticated requests and malformed input. A project with a handful of public content routes and two roles needs far less work than one with dozens of custom endpoints, ownership checks and per-role permission rules. Count these items first, because they set the number of test cases and the fixtures each case needs.

Does our team need to already run Jest to start?

No, but it helps. If your engineers already write Jest unit tests for Node.js code, the work shifts to Supertest setup, an in-memory test database and authenticated request helpers. If nobody on the team has used Jest, add time for tooling, conventions and a first set of reviewed tests. Ask whether your Strapi project is TypeScript or JavaScript, because that changes the test configuration and how typed fixtures are written.

What do editors and engineers need to provide for the tests?

Engineers need the custom route, policy and permission definitions, plus a clear description of what each role may read, create, update and delete. Editors or product owners need to confirm the expected behavior for each role, because a test can only check the rule someone has written down. Fixtures also need realistic but non-sensitive sample content for each content type involved. Plan a review session where editors sign off on the role matrix before engineers encode it.

Can an internal team own the test suite after it is built?

Yes, if the team can maintain it. Ownership works best when the suite follows one pattern for setup, login and assertions, and when the team knows how to add a case when a route or permission changes. Ask any partner to hand over the test code in your repository, document how to run it locally and in CI, and walk your engineers through adding a new permission test. Ongoing upkeep is a recurring cost, because every Strapi upgrade and schema change can break existing tests.

How do Strapi upgrades and schema changes affect test effort?

They add recurring effort. Strapi 5 releases ship often, and minor versions such as v5.58.0 change the platform underneath your code. Each upgrade may require updating tests, fixtures or helper functions, and a schema change may require new fixtures. Budget for regression runs whenever you upgrade Strapi, and ask whether the scope includes a first run against the latest supported release.

What should be in a written scope for the test suite?

A written scope should list the endpoints and content types covered, the roles and authentication methods tested, the database used for tests, and the CI pipeline the suite must run in before each deployment. It should also name the deliverables: test code in your repository, fixtures, a short run guide and a handover session. Ask for explicit exclusions, such as load testing or end-user front-end tests, so both sides know what is not included.

What does the work cost, and is it one-time or recurring?

The initial build is a one-time cost covering setup, the first set of tests and handover. Upkeep, such as updating tests after upgrades and adding cases for new features, recurs. DeployOpen does not publish prices, so ask for a quote based on the written scope. Compare the quote with the internal time your engineers would spend learning Jest, Supertest and Strapi's test patterns, plus the time to maintain the suite once they own it.

Does the test suite cover security checks on Strapi permissions?

It covers the permissions you define, which is why the role matrix matters. Tests can confirm that an unauthenticated request is denied, that a reader cannot write, and that a user cannot read another user's records when ownership rules apply. They do not replace a security review of your overall Strapi configuration. Ask whether the scope includes checks for public permissions and token handling, or whether those belong in a separate review.

How DeployOpen scopes and delivers a Strapi test suite

DeployOpen plans and builds self-hosted open-source platforms inside the client's own infrastructure, and treats a Strapi API test suite as a deliverable in its own right. Work starts with a written scope that names the content types, routes and permission rules to cover, then moves through build, handover and optional ongoing support.

How we scope

  • We list the Strapi routes, custom controllers and Users & Permissions rules that the test suite must cover.
  • We agree in writing which roles, public and authenticated requests, and failure cases are in scope.
  • We confirm the Node.js, database and CI environment the suite must run in before work begins.

How we build

  • We configure Jest and Supertest against an in-memory SQLite Strapi instance with seeded test data.
  • We write authenticated request helpers for each role and test ownership and permission boundaries explicitly.
  • We wire the suite into your CI pipeline so it runs before each deployment and blocks release on failure.

How we hand over

  • You receive the test code, fixtures, helper utilities and a README explaining how to run the suite locally.
  • We document the CI configuration, environment variables and known gaps so your team can extend tests later.
  • We walk your engineers through adding a new endpoint test and reading failure output before we close the engagement.

How we support

  • Engagements are fixed-scope, with deliverables and timelines agreed in writing before work starts.
  • Ongoing support, upgrades and continuous testing are available as a retainer, including updates for new Strapi 5 releases.
  • Ask us to confirm the support terms, response expectations and included upgrade work in the written quote.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.