Skip to content

🚀 Feature Request: per-test environment #7339

@terinjokes

Description

@terinjokes

Describe the solution

There are three arguments to fetch: the incoming Request, the environment, and an ExecutionContext. The request is usually constructed per-test (and is a primary input to the code under test), the context is also created per-test using the createExecutionContext function exported from cloudflare:test. The lifecycle of these are clear and understandable.

The environment, on the other hand, is a global, imported from cloudflare:test and reused across all tests. While storage (like KV) is reset between tests, the env object is not, nor is it frozen. Mutations from one test affect all others that run afterwards.

I would like a function (tentatively and unimaginatively) named createEnvironment. This function can be used to create an environment for each test, where mutations have a clear lifecycle.

import { createEnvironment } from "cloudflare:test";
import { test } from "vitest";

test('modification a', ({ expect }) => {
  const env = createEnvironment();
  env.token = "test";
  expect(env.token).toBe("test");
})
  
test('no modification', ({ expect }) => {
  const env = createEnvironment();
  expect(env.token).toBeUndefined();
})

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestvitestRelating to the Workers Vitest integration

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions