Skip to content

Recipes

Tugkan Boz edited this page Jun 4, 2026 · 1 revision

Recipes

Log in, then use the token

import { session } from "two-go";

const s = session(process.env.BASE_URL);
await s.post("/auth/login").json({ email, password }).extract("token", "data.token");
await s.get("/account").header("authorization", "Bearer {{token}}").expectOk();

Wait for a flaky or async endpoint

import { eventually, pollUntil } from "two-go";

await eventually(() => api.get("/report/42").expectJson("ready", true),
  { timeout: 10000, interval: 500 });

const done = await pollUntil(
  () => api.get("/jobs/123"),
  (r) => r.get("status") === "done",
  { timeout: 5000, interval: 200 });

Retry a request

await api.get("/flaky").retry({ attempts: 3, delay: 200, on: (r) => r.status >= 500 });

Data-driven tests

const cases = [
  { id: 1, status: 200 },
  { id: 999999, status: 404 },
];
for (const c of cases) {
  test(`GET /users/${c.id} -> ${c.status}`, async () => {
    await api.get(`/users/${c.id}`).expectStatus(c.status);
  });
}

Contract test from a known-good response

import { inferSchema } from "two-go";
const golden = (await api.get("/users")).body;
const schema = inferSchema(golden);
await api.get("/users").expectJsonSchema(schema);

Snapshot a response

import { toMatchSnapshot } from "two-go";
const res = await api.get("/users");
toMatchSnapshot(res.body, "users-list"); // first run writes, later runs compare

GraphQL

await go(endpoint).graphql("{ user { id } }", { id: 1 })
  .expectStatus(200)
  .expectJson("data.user.id", 1);

Fake data

import { faker } from "two-go";
const payload = { id: faker.uuid(), email: faker.email(), name: faker.fullName() };

CI (GitHub Actions)

- uses: actions/setup-node@v4
  with: { node-version: 20 }
- run: npm test

Docker, and a microservice with MySQL/MSSQL

See two-go-examples/microservice for a full Docker Compose setup that brings up the service plus its databases and runs the suite, exiting with the test result.

Clone this wiki locally