<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sebastián Chikán on Medium]]></title>
        <description><![CDATA[Stories by Sebastián Chikán on Medium]]></description>
        <link>https://medium.com/@sebastinchikn?source=rss-3f355caec789------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Sebastián Chikán on Medium</title>
            <link>https://medium.com/@sebastinchikn?source=rss-3f355caec789------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 01:55:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sebastinchikn/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Run Jest Integration Tests in Parallel Using Isolated SQL Schemas]]></title>
            <link>https://medium.com/@sebastinchikn/how-to-run-jest-integration-tests-in-parallel-using-isolated-sql-schemas-f4c5e534030a?source=rss-3f355caec789------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4c5e534030a</guid>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[prisma]]></category>
            <dc:creator><![CDATA[Sebastián Chikán]]></dc:creator>
            <pubDate>Tue, 13 Jan 2026 07:42:53 GMT</pubDate>
            <atom:updated>2026-01-13T07:42:53.215Z</atom:updated>
            <content:encoded><![CDATA[<p>In one of our TypeScript/Node.js services, most of our confidence comes from <strong>integration tests</strong>, with a deliberately thin layer of unit tests applied only where<strong> business logic is sufficiently complex</strong> to require focused verification. Tests are executed using Jest, backed by a Postgres instance running in Docker as the test database, with Prisma providing the data access layer.</p><p>Most of the service’s responsibility lies in communication rather than decision-making: maintaining SSE streams, handling HTTP requests, and relaying data to other internal services.</p><p>At <strong>Dakai.io</strong>, we initially ran our integration <strong>tests in parallel without clearing the database</strong>, relying instead on practical isolation by creating test data with <strong>unique UUIDs</strong>. This allowed tests to execute safely at the same time — up to a point.</p><h3>Why not clear the database?</h3><p>When running tests with Jest in parallel, test files can execute concurrently, while tests within the same file run sequentially. If multiple test files operate on the same tables, <strong>clearing the database between tests can cause one test to accidentally remove data that another test is still using</strong>, leading to intermittent and hard-to-debug failures.</p><p>This is why simply wiping tables between tests isn’t always a safe solution.</p><h4>Tests with UUIDs</h4><p>To address this, we<strong> generate unique UUIDs for all test data.</strong> Each test operates on its own records, preventing interference with other parallel tests and making it safe to run tests concurrently without wiping the tables.</p><p>The following codes are very simple examples to <strong>illustrate the concept </strong>— these are not full production-grade integration tests.</p><pre>it(&#39;getUserById returns the proper user&#39;, async () =&gt; {<br>  // unique ID for this test<br>  const testId = uuidv4(); <br>  // unique name to make sure the user we retrieve is exactly the one created in this test<br>  const testUserName = `Test User ${uuidv4()}`; <br>  await createTestUser({ id: testId, name: testUserName });<br><br>  const user = await getUserById(testId);<br><br>  expect(user.name).toEqual(testUserName);<br>});</pre><p>This approach works perfectly for tests that create and retrieve individual records. However,<strong> it breaks down when testing endpoints like </strong><strong>listUsers, which return global entities that cannot be scoped or filtered by UUID.</strong> In such cases, tests can interfere with each other, and parallel execution may lead to <strong>flaky results</strong><em> </em>— like in this one:</p><pre>it(&#39;listUsers returns all the users&#39;, async () =&gt; {<br>  const testUserName1 = `Test User1 ${uuidv4()}`; <br>  const testUserName2 = `Test User2 ${uuidv4()}`;<br>  <br>  await createTestUser({ id: uuidv4(), name: testUserName1 });<br>  await createTestUser({ id: uuidv4(), name: testUserName2 });<br><br>  const usersResponse = await listUsers();<br><br>  const userNames = usersResponse.map(u =&gt; u.name);<br>  expect(userNames.length).toEqual(2);<br>  expect(userNames).toContain(testUserName1);<br>  expect(userNames).toContain(testUserName2);<br>});</pre><p>At this point, if we want <strong>fully deterministic results with strong assertions</strong>, <strong>there is effectively no alternative to resetting the relevant tables</strong> before each test run.</p><h4>The hard decision</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/0*wJ56MBLooW6IgpDO.jpg" /><figcaption>Matrix</figcaption></figure><p>As we saw earlier,<strong> cleaning the tables while running tests in parallel doesn’t work well on a shared database.</strong> This seems to leave us with <strong>two unappealing options: run tests sequentially, or weaken our assertions</strong> so they no longer require a clean database.</p><p>This decision would be even harder than the one Keanu faced in the movie — we don’t want to accept compromises this big.</p><h4>Jest Under the Hood: Running Tests in Parallel</h4><p>When running Jest tests in parallel, <strong>the number of workers is determined based on the configuration and/or the number of CPU cores available on the host machine.</strong></p><p><strong>Each worker runs in its own separate Node.js process and</strong> <strong>handles one test file at a time</strong>, so the tests within a single file are executed sequentially, as we discussed earlier.</p><p>This setup allows Jest to fully utilize the available CPU cores, but it also introduces a challenge: <strong>multiple workers can access the same database tables simultaneously</strong>, which may lead to interference between tests if the data isn’t properly isolated.</p><h4>Solution: separate DB schema for each worker</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UiJgenRxG8iGLij1isIxZA.png" /><figcaption><strong>Big picture of the process</strong></figcaption></figure><p>By <strong>creating a separate schema for each worker</strong> and configuring them to <strong>read and write only to their assigned schema</strong>, we can ensure an isolated environment where tests don’t interfere with each other. <strong>Each worker still runs the tests in its own process sequentially, so parallel execution across workers is safe and isolated.</strong> This may sound more complicated than it actually is.</p><p>First we needed to create the setup that <strong>starts the database </strong>and <strong>calculates the number of workers that will be needed.</strong> This can be easily done since we use <strong>maxWorkers = 50%</strong> and the <a href="https://github.com/jestjs/jest/blob/94830794dc5dfca1b49bc435b7b031b27838a798/packages/jest-config/src/getMaxWorkers.ts#L11">exact implementation is available</a>.</p><p>Even if you rely on Jest’s default worker calculation, this setup still works the same way — you only need to understand how many workers will be spawned so you can create the corresponding schemas.</p><p>After this we <strong>create a schema for each worker</strong> (for example: test_worker_1) and <strong>run the migrations on those schemas</strong>. This setup/migration has to be run only once.</p><pre>const os = require(&#39;os&#39;)<br>const { Client } = require(&#39;pg&#39;);<br>const path = require(&#39;path&#39;);<br>const { execSync } = require(&#39;child_process&#39;);<br>const fs = require(&#39;fs&#39;);<br>const { v2: dockerCompose } = require(&#39;docker-compose&#39;)<br>const waitOn = require(&#39;wait-on&#39;)<br><br>const repoRoot = path.resolve(__dirname);<br>const delay = (ms) =&gt; new Promise((res) =&gt; setTimeout(res, ms))<br><br>function loadJestConfig() {<br>  const configPathJS = path.join(repoRoot, &#39;jest.config.js&#39;);<br>  const configPathTS = path.join(repoRoot, &#39;jest.config.ts&#39;);<br><br>  let config;<br><br>  if (fs.existsSync(configPathJS)) {<br>    config = require(configPathJS);<br>  } else if (fs.existsSync(configPathTS)) {<br>    config = require(configPathTS);<br>  } else {<br>    throw new Error(&#39;Cannot find jest.config.js or jest.config.ts&#39;);<br>  }<br><br>  return config;<br>}<br><br>/*<br>  Jest calculates the number of workers (parallel test processes) based on CPU cores:<br>    - If maxWorkers is a number → use that value directly.<br>    - If maxWorkers is a percentage (e.g. &quot;50%&quot;) → use that percentage of available CPU cores, rounded down.<br>    - Otherwise (default) → workers = CPU core count.<br>  Reference:<br>  https://github.com/facebook/jest/blob/main/packages/jest-worker/src/index.ts#L102-L110<br>*/<br>function getWorkerCount(jestConfig) {<br>  if (jestConfig.maxWorkers) {<br>    if (typeof jestConfig.maxWorkers === &#39;number&#39;) return jestConfig.maxWorkers;<br><br>    if (typeof jestConfig.maxWorkers === &#39;string&#39;) {<br>      if (jestConfig.maxWorkers.endsWith(&#39;%&#39;)) {<br>        // e.g. &#39;50%&#39;<br>        const pct = Number(jestConfig.maxWorkers.replace(&#39;%&#39;, &#39;&#39;));<br>        const cores = os.cpus().length;<br>        return Math.max(1, Math.floor((pct / 100) * cores));<br>      }<br><br>      return Number(jestConfig.maxWorkers);<br>    }<br>  }<br><br>  // fallback: number of CPU cores<br>  return require(&#39;os&#39;).cpus().length;<br>}<br><br><br>const baseUrl =<br>  process.env.DATABASE_URL_BASE ||<br>  &#39;postgres://postgres:root@127.0.0.1:5433/postgres&#39;;<br><br>async function startDb() {<br>  await dockerCompose.upOne(&#39;test-db&#39;, {<br>    config: &#39;../../docker-compose-dev-dependencies.yml&#39;<br>  })<br>  await waitOn({ resources: [&#39;tcp:127.0.0.1:5433&#39;], timeout: 30_000 })<br>  // unfortunately even if the port 5432 is open postgres is still not able to run queries, so we wait an arbitrary amount (1s)<br>  await delay(1000)<br>}<br><br>async function createSchema(schemaName) {<br>  const client = new Client({ connectionString: baseUrl });<br><br>  try {<br>    await client.connect();<br>    await client.query(`CREATE SCHEMA IF NOT EXISTS &quot;${schemaName}&quot;;`);<br>  } finally {<br>    await client.end();<br>  }<br>}<br><br>function runPrismaFor(schema) {<br>  process.env.DATABASE_URL = `${baseUrl}?schema=${schema}`;<br><br>  console.log(`\n🟦 Migrating schema: ${schema}`);<br>  execSync(`npx turbo run prisma:migrate --filter @api/storage`, {<br>    stdio: &#39;inherit&#39;,<br>    cwd: repoRoot,<br>  });<br><br>  console.log(`🟩 Seeding schema: ${schema}`);<br>  execSync(`npx turbo run prisma:seed --filter @api/storage`, {<br>    stdio: &#39;inherit&#39;,<br>    cwd: repoRoot,<br>  });<br>}<br><br><br>async function main() {<br>  console.log(&#39;\n=== Jest Worker Schema Setup ===&#39;);<br><br>  await startDb()<br><br>  const jestConfig = loadJestConfig();<br>  const workerCount = getWorkerCount(jestConfig);<br><br>  console.log(`Detected Jest workers: ${workerCount}\n`);<br><br>  for (let i = 1; i &lt;= workerCount; i++) {<br>    const schema = `test_worker_${i}`;<br>    console.log(`\n🔧 Setting up schema: ${schema}`);<br><br><br>    await createSchema(schema);<br>    runPrismaFor(schema);<br>  }<br><br>  console.log(&#39;\n✅ All worker schemas ready.\n&#39;);<br>}<br><br>main().catch((err) =&gt; {<br>  console.error(&#39;❌ Setup failed:&#39;, err);<br>  process.exit(1);<br>});</pre><p>The Database and its schemas are ready, but <strong>how will each worker know which schema to reach out to?</strong></p><p>In the Jest config, we need to <strong>introduce a setup</strong> to ensure each worker is assigned the correct schema.</p><pre>setupFiles: [&#39;./jest-setup.js&#39;],</pre><p><strong>SetupFiles runs once for each worker</strong> after its process is initiated, but <strong>before any tests are executed</strong>. Here is what is inside jest-setup.js :</p><pre>const isCI = require(&#39;is-ci&#39;)<br>if(!isCI) { // on CI we fall back to sequential tests!<br>  process.env.DATABASE_URL = `postgres://postgres:root@127.0.0.1:5433/postgres<br>    ?schema=test_worker_${process.env.JEST_WORKER_ID}`<br>}</pre><p>Each Jest worker runs in <strong>its own Node.js process</strong>, with its <strong>own copy of</strong> process.env, so setting a different DATABASE_URL in each worker keeps the database configuration completely isolated per process.</p><p>The most important thing to look out here is the JEST_WORKER_ID <strong>environment variable.</strong> This is the ID of the given worker and since we used to create schemas like test_worker_1 … test_worker_n this way we can tell each worker <strong>which schema to connect to via the</strong> DATABASE_URL <strong>environment variable</strong> that is used by Prisma.</p><p>⚠️ <strong>Important</strong>: this solution is for running local only, but also could work on CI/CD pipelines that have a strong machine under them. The is-ci package is used here to detect if the test was run in CI/CD and to skip this part. Most <a href="https://stackoverflow.com/questions/43864793/why-does-jest-runinband-speed-up-tests">CI/CD machines are relatively weak</a>, so the recommended approach there is to <strong>run tests sequentially</strong>. <a href="https://medium.com/adobetech/improve-jest-runner-performance-a8f56708ba94">Read more about Jest runner performance</a>.</p><h3>Conclusion</h3><p>In this article, we explored the challenges of running Jest integration tests in parallel. Using <strong>unique UUIDs</strong> works well for individual records, but when dealing with <strong>global entities</strong>, tests can interfere with each other. By implementing a <strong>separate schema for each worker</strong>, we can create an <strong>isolated environment where tests don’t interfere</strong>, allowing safe parallel execution.</p><p>The key takeaway: <strong>proper isolation is essential for reliable parallel tests</strong>, and understanding how Jest workers interact with your database can save you from flaky test results.</p><p>Give this setup a try in your own projects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4c5e534030a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>