Testing your app

4 min read · Edit this page on GitHub

A handler is a function of a request, a loader is a function of its context, and both are tested by calling them. borgo ships two small sets of helpers so that a test says what it is about and not how a request is built.

Nothing on this page listens on a port. For the app as a whole — a build, a browser, a database — use whatever you already use; this repository's e2e/ directory is Playwright against the example app under borgo start.

Go: borgotest#

package api

import (
	"net/http"
	"testing"

	"github.com/LuigiDavideMicca/borgo/borgotest"
)

func TestOnlyTheOwnerDeletes(t *testing.T) {
	// a request as the generated client sends it, made by user 2
	r := borgotest.As(borgotest.Request(t, "DELETE /api/tasks/7", nil), Me{UserID: 2})
	borgotest.SetPath(r, "id", "7")
	borgotest.Do(t, http.HandlerFunc(DeleteTask), r).Status(t, http.StatusForbidden)
}

func TestCreateAnswersWhatWasMade(t *testing.T) {
	r := borgotest.As(borgotest.Request(t, "POST /api/tasks", NewTask{Title: "write the docs"}), Me{UserID: 7})
	var made Task
	borgotest.Do(t, http.HandlerFunc(CreateTask), r).Status(t, http.StatusCreated).JSON(t, &made)
	if made.Title != "write the docs" {
		t.Fatalf("%+v", made)
	}
}
Request(t, "METHOD /path", body) A request for that path. A body that is not nil is sent as JSON with the Content-Type borgo.Bind asks for; with nil there is neither, and Bind answers 415 as it does to a browser that sends none.
As(r, session) The request made by whoever session describes: borgo.GetSession in the handler reads it. It is borgo.WithSession: no cookie, no SESSION_SECRET, and CheckSession is not asked.
SetPath(r, "id", "7") The values a route's pattern would have taken from the path, for a handler called without a mux. Through a mux the pattern fills them.
Do(t, handler, r) Runs the handler inside the chain borgo.Serve puts around every route, so a panic answers 500 and the cookie-and-cache guard runs, and returns what was written.
.Status(t, want) Fails the test when the status is another, and prints the body, which is usually where the reason is.
.JSON(t, &v) Decodes the body into v.
.Cookie(name) The cookie of that name the handler set, or nil.

What Do does not run is api/middleware.go and the CSRF check: those belong to the server, not to a handler. To test a middleware of your own, wrap the handler in it before handing it to Do. To test a rule that depends on a real session cookie — a revocation in CheckSession, say — set SESSION_SECRET with t.Setenv, write a session with borgo.SetSession in one request and send its cookie on the next.

A handler that reads a database is tested against a database: borgo has no opinion on which, and nothing to fake one with.

TypeScript: borgo-framework/testing#

import { expect, test } from "bun:test";
import { actionContext, loaderContext, refused } from "borgo-framework/testing";
import { action, loader } from "../pages/tasks";

test("the page shows the tasks of whoever is signed in", async () => {
  const context = loaderContext({
    url: "/tasks?done=1",
    session: { userId: 7 },
    api: { "GET /api/tasks": ({ query }) => ({ tasks: [{ id: 1, title: "x", done: query?.done }] }) },
  });
  const props = await loader(context);
  expect(props.tasks).toHaveLength(1);
  expect(context.calls[0].query).toEqual({ done: true });
});

test("a name that is taken comes back as the form's error", async () => {
  const data = await action(
    actionContext({
      form: { title: "write the docs" },
      session: { userId: 7 },
      api: { "POST /api/tasks": refused(409, { error: "there is one by that name" }) },
    }),
  );
  expect(data).toEqual({ error: "there is one by that name" });
});

loaderContext(init) builds everything a loader is handed, once included, from the few things a test cares about:

Field
url A path or a whole address. Default /.
params The values of the route's [param] segments.
session Who is signed in. Nobody when absent.
locals What api/middleware.go would have handed over.
headers, method, body For the Request.
api The answers of the api routes the loader calls, by route: a value, or a function of the params, query and body it was called with. An Error as an answer is what the call throws; refused(status, body) makes the ApiError a refusal is.

A route the loader calls and the test gave no answer for fails the test with the route's name: a loader that starts calling another route should say so in its tests. The calls made are in context.calls, in order.

actionContext is the same for an action, with form for the fields a form posts — a string, or several for a field sent more than once — and POST for a method.

The api given here is not typed against your routes: a wrong route name is caught by the loader's own types, where it is called, and an answer of the wrong shape by whatever the loader does with it.