untainer
Get started

A VM in Vitest tests

Run tests against a real Postgres, Redis or a server of your own in Vitest, without Docker on the machine that runs them.

Tests that need a real Postgres, Redis or a server of your own, without Docker on the machine that runs them. This is how untainer tests itself.

#One runtime per file

Booting a VM takes a fraction of a second; starting an image takes longer the first time (its chunks are fetched) and little after that. Boot one runtime per test file and stop it at the end. This file runs as it is: it starts the published hello test image, a small web server, pinned by its tag:

hello.test.ts
import { afterAll, beforeAll, expect, test } from 'vitest';
import { createRuntime, type Container, type Runtime } from 'untainer';

let rt: Runtime;
let web: Container;

beforeAll(async () => {
  rt = await createRuntime({ images: ['gh:OskarLebuda/untainer-images/hello#hello-78fc67baa844'] });
  web = await rt.run('hello');
  await web.ready();
}, 120_000);

afterAll(() => rt?.shutdown());

test('the page', async () => {
  const res = await web.fetch('/');
  expect(await res.text()).toBe('hello from untainer\n');
});

test('a command in the container', async () => {
  const r = await web.exec('cat', ['/www/index.html']);
  expect(r.exitCode).toBe(0);
  expect(r.stdout).toContain('hello from untainer');
});
  • Give the hooks a long timeout: the first run fetches the image (later runs read it from ~/.cache/untainer/chunks).
  • Each test file gets its own VM, so files run in parallel without sharing a database.
  • For an image of your own, build it (untainer build postgres:17-alpine) and publish it (see Hosting), or load its directory with loadImage().
  • A container that should start clean for each test: rt.run() in beforeEach and stop() in afterEach. What takes the time is the command's own start: Postgres runs initdb first, about 6 s on Node (docs/findings.md, "The real build, measured").

#Reaching the container

  • container.exec() runs a command in it and returns its output and exit code.
  • container.fetch('/path', { port }) sends an HTTP request to a server in it.
  • container.connect(port) opens a TCP connection, for a client library that takes a socket.
  • On Node, publishPort(container, { hostPort: 0, containerPort: 5432 }) serves the port on 127.0.0.1 for a client that wants a host and a port.

#In CI

Nothing to install: the VM is WebAssembly in Node. The cache directory (~/.cache/untainer) is worth caching between runs: images and the build's toolbox are kept there.

untainer  OCI images as containers in a browser tab or in Node.