rays/worker/simulate

Build requests, bindings, and contexts for unit testing Worker handlers without the Workers runtime.

Handlers are ordinary functions, so a test calls one directly with a simulated request and asserts on the Gleam Response it returns.

import gleam/http
import gleam/javascript/promise
import gleam/json
import rays/worker/simulate

pub fn create_person_test() {
  let request =
    simulate.request(http.Post, "/people")
    |> simulate.json_body(json.object([#("name", json.string("Joe"))]))
  let env = simulate.env() |> simulate.env_var("GREETING", "Hello")
  let ctx = simulate.context()

  use response <- promise.await(
    app.handle_request(request, env, ctx),
  )
  use background <- promise.map(simulate.wait_for_background(ctx))
  assert response.status == 201
  assert background == Ok(Nil)
  assert simulate.read_body(response) == "{\"name\":\"Joe\"}"
}

Simulated contexts track background work registered with wait_until. Await wait_for_background before asserting on its effects or finishing a test. Calls to other Workers can be faked with with_service, but this module does not otherwise emulate Cloudflare services: there are no fake KV namespaces or D1 databases. To test against real bindings, use Cloudflare’s Vitest integration or test harness, which run the compiled Worker in the Workers runtime.

Values

pub fn bit_array_body(
  request: request.Request(worker.RequestBody),
  body: BitArray,
) -> request.Request(worker.RequestBody)

Set the body of the request to the given binary data. The content type is not changed.

Panics

Panics if the bit array is not a whole number of bytes.

pub fn context() -> worker.Context

Create an execution context that tracks work registered with wait_until. Await wait_for_background before finishing a test to observe its completion and failures. pass_through_on_exception does not forward requests.

pub fn env() -> worker.Env

Create an environment with no bindings.

pub fn env_binding(
  env: worker.Env,
  name: String,
  value: dynamic.Dynamic,
) -> worker.Env

Add any value to the environment as a binding, such as a test double you have written for a KV namespace.

pub fn env_var(
  env: worker.Env,
  name: String,
  value: String,
) -> worker.Env

Add a string environment variable or secret to the environment.

Examples

simulate.env()
|> simulate.env_var("API_TOKEN", "secret")
pub fn form_body(
  request: request.Request(worker.RequestBody),
  data: List(#(String, String)),
) -> request.Request(worker.RequestBody)

Set the body of the request to the given form values, URL-encoded, and set the content type to application/x-www-form-urlencoded.

pub fn header(
  request: request.Request(worker.RequestBody),
  name: String,
  value: String,
) -> request.Request(worker.RequestBody)

Set a header on the request, replacing any existing header with the same name.

pub fn html_body(
  request: request.Request(worker.RequestBody),
  html: String,
) -> request.Request(worker.RequestBody)

Set the body of the request to the given HTML, and set the content type to text/html.

pub fn json_body(
  request: request.Request(worker.RequestBody),
  data: json.Json,
) -> request.Request(worker.RequestBody)

Set the body of the request to the given JSON, and set the content type to application/json.

pub fn read_body(
  response: response.Response(worker.Body),
) -> String

Read the body of a response as a string.

Panics

Panics in the same cases as read_body_bits, and if the body is not valid UTF-8.

pub fn read_body_bits(
  response: response.Response(worker.Body),
) -> BitArray

Read the body of a response as a bit array.

Panics

Panics if the body is a stream, which cannot be read synchronously, or is binary data that is not a whole number of bytes, which rays/worker would replace with a 500 response.

pub fn request(
  method: http.Method,
  path: String,
) -> request.Request(worker.RequestBody)

Create a request with the given method and path, which may include a query string. The request has no headers and an empty body, and is sent to https://example.com.

Examples

simulate.request(http.Get, "/users?page=2")
pub fn string_body(
  request: request.Request(worker.RequestBody),
  body: String,
) -> request.Request(worker.RequestBody)

Set the body of the request to the given text. The content type is not changed.

pub fn wait_for_background(
  ctx: worker.Context,
) -> promise.Promise(Result(Nil, dynamic.Dynamic))

Wait for background work registered on a context created by context. This includes work registered by other background tasks while waiting.

Resolves to Error with the first observed native rejection, after all registered work has settled. A fulfilled Error is a value, not a rejection. This does not cancel tasks or impose a timeout, and cannot wait for work registered after all tracked tasks have finished.

pub fn with_rpc_service(
  env: worker.Env,
  name: String,
  context: worker.Context,
  worker: worker.Worker,
  worker_env: worker.Env,
) -> worker.Env

Add a fake service binding to the environment, bound to the given Worker, whose methods can be called with rays/worker_rpc.call.

Calls go straight to the handlers bound with worker_rpc.bind, with worker_env as their bindings and the given context, without encoding the values. So a simulated call doesn’t check that its argument and reply can be sent, or that the two Workers have the same version of the method: test those with the Workers runtime, for example with Cloudflare’s Vitest integration.

Examples

let ctx = simulate.context()
let env =
  simulate.env()
  |> simulate.with_rpc_service("NAMES", ctx, names.main(), simulate.env())
pub fn with_service(
  env: worker.Env,
  name: String,
  context: worker.Context,
  handler: fn(request.Request(worker.RequestBody), worker.Context) -> promise.Promise(
    response.Response(worker.Body),
  ),
) -> worker.Env

Add a fake service binding to the environment. Requests sent to it with rays/fetch are handled by the given function, as if by another Worker.

The request goes through the same conversion as a real request to a Worker, so the handler receives an ordinary Request, together with the given context. Background work the fake registers with wait_until is waited for by wait_for_background on that context, mirroring how the Workers runtime ties a bound Worker’s background work to the caller’s request.

Examples

let ctx = simulate.context()
let env =
  simulate.env()
  |> simulate.with_service("AUTH", ctx, fn(_request, _ctx) {
    worker.ok() |> worker.string_body("joe") |> promise.resolve
  })
✨ Search Document