From e83e4f52ed56039a1df5ecb26a123da8b18642af Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Wed, 29 May 2024 17:04:22 +0200 Subject: [PATCH] vitest: add basic docs (#2868) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Maxwell Brown Co-authored-by: Attila Večerek --- packages/vitest/README.md | 254 +++++++++++++++++++++++++++++++------- 1 file changed, 212 insertions(+), 42 deletions(-) diff --git a/packages/vitest/README.md b/packages/vitest/README.md index 8113be2368..63901d1abe 100644 --- a/packages/vitest/README.md +++ b/packages/vitest/README.md @@ -1,64 +1,234 @@ -# Effect +# Introduction -Welcome to Effect, a powerful TypeScript framework that provides a fully-fledged functional effect system with a rich standard library. +Welcome to your guide on testing Effect applications using `vitest` and the `@effect/vitest` package! `@effect/vitest` is designed to help simplify running Effect-based tests through `vitest`. + +In the guide below, we will first start by setting up the required dependencies. Then, we will dive into a few examples of how to use `@effect/vitest` to create some Effect-based test cases. # Requirements -- TypeScript 5.0 or newer -- The `strict` flag enabled in your `tsconfig.json` file +First, install [`vitest`](https://vitest.dev/guide/) (version `1.6.0` or newer) +```sh +pnpm add -D vitest ``` -{ - // ... - "compilerOptions": { - // ... - "strict": true, - } + +Next, install the `@effect/vitest` package which facilitates running Effect-based tests through `vitest`. + +```sh +pnpm add -D @effect/vitest +``` + +# Overview + +The main entry point is the following import: + +```ts +import { it } from "@effect/vitest" +``` + +This import enhances the standard `it` function from `vitest` with several powerful features, including: + +| Feature | Description | +| --------------- | ------------------------------------------------------------------------------------------------------ | +| `it.effect` | Automatically injects a `TestContext` (e.g., `TestClock`) when running a test. | +| `it.live` | Runs the test with the live Effect environment. | +| `it.scoped` | Allows running an Effect program that requires a `Scope`. | +| `it.scopedLive` | Combines the features of `scoped` and `live`, using a live Effect environment that requires a `Scope`. | +| `it.flakyTest` | Facilitates the execution of tests that might occasionally fail. | + +# Writing Tests with `it.effect` + +Here's how to use `it.effect` to write your tests: + +```ts +import { it } from "@effect/vitest" + +it.effect("test name", () => EffectContainingAssertions, timeout: number | TestOptions = 5_000) +``` + +When using `it.effect`, the `TestContext` is automatically injected, which allows tests to have access to services designed to facilitate testing (such as the [`TestClock`](#using-the-testclock)). + +## Testing Successful Operations + +Let's create a test for a function that divides two numbers but fails if the divisor is zero: + +```ts +import { it } from "@effect/vitest" +import { Effect } from "effect" +import { expect } from "vitest" + +function divide(a: number, b: number) { + if (b === 0) return Effect.fail("Cannot divide by zero") + return Effect.succeed(a / b) } + +it.effect("test success", () => + Effect.gen(function* () { + const result = yield* divide(4, 2) + expect(result).toBe(2) + }) +) ``` -## Documentation +## Testing Successes and Failures as `Exit` -For detailed information and usage examples, please visit the [Effect website](https://www.effect.website/). +To test both success and failure scenarios, convert the outcomes into an `Exit` object using `Effect.exit`: -## Introduction to Effect +```ts +import { it } from "@effect/vitest" +import { Effect, Exit } from "effect" +import { expect } from "vitest" -To get started with Effect, watch our introductory video on YouTube. This video provides an overview of Effect and its key features, making it a great starting point for newcomers: +function divide(a: number, b: number) { + if (b === 0) return Effect.fail("Cannot divide by zero") + return Effect.succeed(a / b) +} + +it.effect("test success as Exit", () => + Effect.gen(function* () { + const result = yield* divide(4, 2).pipe(Effect.exit) + expect(result).toStrictEqual(Exit.succeed(2)) + }) +) + +it.effect("test failure as Exit", () => + Effect.gen(function* () { + const result = yield* divide(4, 0).pipe(Effect.exit) + expect(result).toStrictEqual(Exit.fail("Cannot divide by zero")) + }) +) +``` + +## Using the TestClock -[![Introduction to Effect](https://img.youtube.com/vi/SloZE4i4Zfk/maxresdefault.jpg)](https://youtu.be/SloZE4i4Zfk) +When using `it.effect`, a `TestContext` is provided to your program which provides access to several services designed to facilitate testing. One such service is the `[TestClock`](https://effect.website/docs/guides/testing/testclock) which is designed to simulate the passage of time. -## Connect with Our Community +**Note**: To utilize the default, non-testing services in your tests you can use `it.live`. -Join our vibrant community on Discord to interact with fellow developers, ask questions, and share your experiences. Here's the invite link to our Discord server: [Join Effect's Discord Community](https://discord.gg/hdt7t7jpvn). +Below, you'll find examples illustrating different ways to use time in your tests: -## API Reference +1. **Using `it.live` to show the current time:** This mode uses the real-time clock of your system, reflecting the actual current time. -For detailed information on the Effect API, please refer to our [API Reference](https://effect-ts.github.io/effect/). +2. **Using `it.effect` with no adjustments:** By default, this test starts the clock at a time of `0`, effectively simulating a starting point without any elapsed time. -## Pull Requests +3. **Using `it.effect` and adjusting time forward:** Here, we advance the clock by 1000 milliseconds to test scenarios that depend on the passing of time. -We welcome contributions via pull requests! Here are some guidelines to help you get started: +```ts +import { it } from "@effect/vitest" +import { Clock, Effect, TestClock } from "effect" -1. Fork the repository and clone it to your local machine. -2. Create a new branch for your changes: `git checkout -b my-new-feature`. -3. Ensure you have the required dependencies installed by running: `pnpm install` (assuming pnpm version `8.x`). -4. Make your desired changes and, if applicable, include tests to validate your modifications. -5. Run the following commands to ensure the integrity of your changes: - - `pnpm check`: Verify that the code compiles. - - `pnpm test`: Execute the tests. - - `pnpm circular`: Confirm there are no circular imports. - - `pnpm lint`: Check for code style adherence (if you happen to encounter any errors during this process, you can use `pnpm lint-fix` to automatically fix some of these style issues). - - `pnpm dtslint`: Run type-level tests. - - `pnpm docgen`: Update the automatically generated documentation. -6. Create a changeset for your changes: before committing your changes, create a changeset to document the modifications. This helps in tracking and communicating the changes effectively. To create a changeset, run the following command: `pnpm changeset`. Always choose the `patch` option when prompted (please note that we are currently in pre-release mode). -7. Commit your changes: after creating the changeset, commit your changes with a descriptive commit message: `git commit -am 'Add some feature'`. -8. Push your changes to your fork: `git push origin my-new-feature`. -9. Open a pull request against our `main` branch. +const logNow = Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis + console.log(now) +}) -### Pull Request Guidelines +it.live("runs the test with the live Effect environment", () => + Effect.gen(function* () { + yield* logNow // prints the actual time + }) +) + +it.effect("run the test with the test environment", () => + Effect.gen(function* () { + yield* logNow // prints 0 + }) +) + +it.effect("run the test with the test environment and the time adjusted", () => + Effect.gen(function* () { + yield* TestClock.adjust("1000 millis") + yield* logNow // prints 1000 + }) +) +``` -- Please make sure your changes are consistent with the project's existing style and conventions. -- Please write clear commit messages and include a summary of your changes in the pull request description. -- Please make sure all tests pass and add new tests as necessary. -- If your change requires documentation, please update the relevant documentation. -- Please be patient! We will do our best to review your pull request as soon as possible. +## Skipping Tests + +You can skip a test using `it.effect.skip`, which is useful when you want to temporarily disable a test without deleting any code. + +```ts +it.effect.skip("test failure as Exit", () => + Effect.gen(function* () { + const result = yield* divide(4, 0).pipe(Effect.exit) + expect(result).toStrictEqual(Exit.fail("Cannot divide by zero")) + }) +) +``` + +## Running a Single Test + +To run only a specific test and ignore all others, use `it.effect.only`. This is helpful during development to focus on a single test case. + +```ts +it.effect.only("test failure as Exit", () => + Effect.gen(function* () { + const result = yield* divide(4, 0).pipe(Effect.exit) + expect(result).toStrictEqual(Exit.fail("Cannot divide by zero")) + }) +) +``` + +# Writing Tests with `it.scoped` + +The `it.scoped` method allows you to run tests that involve Effect programs requiring a `Scope`. A `Scope` is essential when your Effect needs to manage resources that must be acquired before the test and released after it completes. This ensures that all resources are properly cleaned up, preventing leaks and ensuring test isolation. + +Here’s a simple example to demonstrate how `it.scoped` can be used in your tests: + +```ts +import { it } from "@effect/vitest" +import { Console, Effect } from "effect" + +// Simulate acquiring and releasing a resource with console logging +const acquire = Console.log("acquire resource") +const release = Console.log("release resource") + +// Define a resource that needs to be managed +const resource = Effect.acquireRelease(acquire, () => release) + +// Incorrect usage: This will result in a type error because it lacks a scope +it.effect("run with scope", () => + Effect.gen(function* () { + yield* resource + }) +) + +// Correct usage: Using 'it.scoped' to properly manage the scope +it.scoped("run with scope", () => + Effect.gen(function* () { + yield* resource + }) +) +``` + +# Writing Tests with `it.flakyTest` + +`it.flakyTest` is a function from the `@effect/vitest` package designed to handle tests that might not succeed on the first try. These tests are often called "flaky" tests because their outcome can vary (e.g., due to timing issues, external dependencies, or randomness). `it.flakyTest` allows these tests to be retried until they succeed or until a specified timeout period expires. + +Here's how you can use `it.flakyTest` in your test suite: + +First, let’s set up a basic test scenario that could potentially fail randomly: + +```ts +import { it } from "@effect/vitest" +import { Effect, Random } from "effect" + +// Define a flaky test effect +const flaky = Effect.gen(function* () { + const random = yield* Random.nextBoolean + if (random) { + return yield* Effect.fail("Failed due to randomness") + } +}) + +// Standard test, which may fail intermittently +it.effect("possibly failing test", () => flaky) +``` + +To address the flakiness, we apply `it.flakyTest` which will retry the test until it succeeds or the specified timeout is reached: + +```ts +// Retrying the flaky test with a timeout +it.effect("retrying until success or timeout", () => + it.flakyTest(flaky, "5 seconds") +) +```