For AI agents: the complete documentation index is available at /byethrow/ja/llms.txt, the full documentation bundle is available at /byethrow/ja/llms-full.txt, and this page is available as Markdown at /byethrow/ja/guide/ecosystem/testing.md.
  • 日本語
  • テスト

    @praha/byethrow-testing は Result をアサートするためのカスタムマッチャーを提供します。テストが短くなり、失敗時のメッセージもわかりやすくなります。

    インストール

    npm
    yarn
    pnpm
    bun
    deno
    npm install -D @praha/byethrow-testing

    セットアップ

    セットアップファイルでマッチャーを登録し、テストランナーの設定からそのファイルを読み込みます。

    Vitest

    vitest.setup.ts
    import { 
    import resultMatchers
    resultMatchers
    } from '@praha/byethrow-testing';
    import {
    const expect: ExpectStatic
    expect
    } from 'vitest';
    import type {
    interface ResultMatchers<R, T>
    ResultMatchers
    } from '@praha/byethrow-testing';
    declare module 'vitest' { interface
    interface Matchers<R extends void | Promise<void> = void | Promise<void>, T = unknown>
    Matchers
    <
    function (type parameter) R in Matchers<R extends void | Promise<void> = void | Promise<void>, T = unknown>
    R
    ,
    function (type parameter) T in Matchers<R extends void | Promise<void> = void | Promise<void>, T = unknown>
    T
    > extends
    interface ResultMatchers<R, T>
    ResultMatchers
    <
    function (type parameter) R in Matchers<R extends void | Promise<void> = void | Promise<void>, T = unknown>
    R
    ,
    function (type parameter) T in Matchers<R extends void | Promise<void> = void | Promise<void>, T = unknown>
    T
    > {}
    }
    const expect: ExpectStatic
    expect
    .
    ExpectStatic.extend: (expects: MatchersObject) => void
    extend
    (
    import resultMatchers
    resultMatchers
    );
    vitest.config.ts
    import { 
    function defineConfig(config: UserConfig): UserConfig (+4 overloads)
    defineConfig
    } from 'vitest/config';
    export default
    function defineConfig(config: UserConfig): UserConfig (+4 overloads)
    defineConfig
    ({
    UserConfig.test?: InlineConfig | undefined

    Options for Vitest

    test
    : {
    InlineConfig.setupFiles?: string | string[] | undefined

    Path to setup files

    setupFiles
    : ['./vitest.setup.ts'],
    }, });

    Jest

    jest.setup.ts
    import { 
    const expect: JestExpect
    expect
    } from '@jest/globals';
    import {
    import resultMatchers
    resultMatchers
    } from '@praha/byethrow-testing';
    import type {
    interface ResultMatchers<R, T>
    ResultMatchers
    } from '@praha/byethrow-testing';
    declare module 'expect' { interface
    interface Matchers<R extends void | Promise<void>, T = unknown>
    Matchers
    <
    function (type parameter) R in Matchers<R extends void | Promise<void>, T = unknown>
    R
    ,
    function (type parameter) T in Matchers<R extends void | Promise<void>, T = unknown>
    T
    > extends
    interface ResultMatchers<R, T>
    ResultMatchers
    <
    function (type parameter) R in Matchers<R extends void | Promise<void>, T = unknown>
    R
    ,
    function (type parameter) T in Matchers<R extends void | Promise<void>, T = unknown>
    T
    > {}
    }
    const expect: JestExpect
    expect
    .
    BaseExpect.extend(matchers: MatchersObject): void
    extend
    (
    import resultMatchers
    resultMatchers
    );
    jest.config.ts
    export default {
      
    setupFilesAfterEnv: string[]
    setupFilesAfterEnv
    : ['./jest.setup.ts'],
    };

    Rstest

    rstest.setup.ts
    import { 
    import resultMatchers
    resultMatchers
    } from '@praha/byethrow-testing';
    import {
    const expect: ExpectStatic
    expect
    } from '@rstest/core';
    import type {
    interface ResultMatchers<R, T>
    ResultMatchers
    } from '@praha/byethrow-testing';
    declare module '@rstest/core' { interface
    interface Matchers<T = any>
    Matchers
    <
    function (type parameter) T in Matchers<T = any>
    T
    > extends
    interface ResultMatchers<R, T>
    ResultMatchers
    <void,
    function (type parameter) T in Matchers<T = any>
    T
    > {}
    }
    const expect: ExpectStatic
    expect
    .
    extend: (expects: MatchersObject<MatcherState>) => void
    extend
    (
    import resultMatchers
    resultMatchers
    );
    rstest.config.ts
    import { 
    function defineConfig<const Config extends RstestConfig, const Definition extends Config | (() => Config) | (() => Promise<Config>)>(config: Definition & (Definition extends (...args: never[]) => infer CallbackResult ? [Awaited<CallbackResult>] extends [RstestConfig] ? unknown : never : RstestConfig & Record<Exclude<keyof Definition, keyof RstestConfig>, never>)): Definition extends (...args: never[]) => infer CallbackResult ? [CallbackResult] extends [RstestConfig] ? RstestConfigSyncFn : RstestConfigAsyncFn : RstestConfig (+4 overloads)

    This function helps you to autocomplete configuration types. It accepts a Rstest config object, or a function that returns a config.

    defineConfig
    } from '@rstest/core';
    export default
    defineConfig<RstestConfig, {
        readonly setupFiles: ["./rstest.setup.ts"];
    }>(config: {
        readonly setupFiles: ["./rstest.setup.ts"];
    } & RstestConfig & Record<never, never>): RstestConfig (+4 overloads)

    This function helps you to autocomplete configuration types. It accepts a Rstest config object, or a function that returns a config.

    defineConfig
    ({
    setupFiles: (["./rstest.setup.ts"] & string) | (["./rstest.setup.ts"] & string[])

    Path to setup files. They will be run before each test file.

    setupFiles
    : ['./rstest.setup.ts'],
    });

    マッチャー

    toBeSuccess(callback?)

    受け取った値が Success であることをアサートします。 コールバックを渡すと、成功値に対してさらにアサーションを行えます。

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    import {
    const test: TestAPI

    Defines a test case with a given name and test function. The test function can optionally be configured with test options.

    @paramname - The name of the test or a function that will be used as a test name.@paramoptionsOrFn - Optional. The test options or the test function if no explicit name is provided.@paramoptionsOrTest - Optional. The test function or options, depending on the previous parameters.@throws{Error} If called inside another test function.@example
    // Define a simple test
    test('should add two numbers', () => {
      expect(add(1, 2)).toBe(3);
    });
    @example
    // Define a test with options
    test('should subtract two numbers', { retry: 3 }, () => {
      expect(subtract(5, 2)).toBe(3);
    });
    test
    ,
    const expect: ExpectStatic
    expect
    } from 'vitest';
    test<object>(name: string | Function, fn?: TestFunction<object> | undefined, options?: number): void (+1 overload)

    Defines a test case with a given name and test function. The test function can optionally be configured with test options.

    @paramname - The name of the test or a function that will be used as a test name.@paramoptionsOrFn - Optional. The test options or the test function if no explicit name is provided.@paramoptionsOrTest - Optional. The test function or options, depending on the previous parameters.@throws{Error} If called inside another test function.@example
    // Define a simple test
    test('should add two numbers', () => {
      expect(add(1, 2)).toBe(3);
    });
    @example
    // Define a test with options
    test('should subtract two numbers', { retry: 3 }, () => {
      expect(subtract(5, 2)).toBe(3);
    });
    test
    ('result is success', () => {
    const
    const result: Result.Result<42, never>
    result
    =
    import Result
    Result
    .
    function succeed<42>(value: 42): Result.Result<42, never> (+1 overload)

    Creates a Success result from a given value.

    Passing a Promise is allowed, but it is recommended to await it before passing to succeed.

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed(42);
    // Result.Result<42, never>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed();
    // Result.Result<void, never>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    succeed
    (42);
    expect<Result.Result<42, never>>(actual: Result.Result<42, never>, message?: string): Assertion<void, Result.Result<42, never>> (+1 overload)
    expect
    (
    const result: Result.Result<42, never>
    result
    ).
    ResultMatchers<void, Result<42, never>>.toBeSuccess: (callback?: ((value: 42) => void) | undefined) => void
    toBeSuccess
    ();
    });
    test<object>(name: string | Function, fn?: TestFunction<object> | undefined, options?: number): void (+1 overload)

    Defines a test case with a given name and test function. The test function can optionally be configured with test options.

    @paramname - The name of the test or a function that will be used as a test name.@paramoptionsOrFn - Optional. The test options or the test function if no explicit name is provided.@paramoptionsOrTest - Optional. The test function or options, depending on the previous parameters.@throws{Error} If called inside another test function.@example
    // Define a simple test
    test('should add two numbers', () => {
      expect(add(1, 2)).toBe(3);
    });
    @example
    // Define a test with options
    test('should subtract two numbers', { retry: 3 }, () => {
      expect(subtract(5, 2)).toBe(3);
    });
    test
    ('result is success with value', () => {
    const
    const result: Result.Result<42, never>
    result
    =
    import Result
    Result
    .
    function succeed<42>(value: 42): Result.Result<42, never> (+1 overload)

    Creates a Success result from a given value.

    Passing a Promise is allowed, but it is recommended to await it before passing to succeed.

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed(42);
    // Result.Result<42, never>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed();
    // Result.Result<void, never>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    succeed
    (42);
    expect<Result.Result<42, never>>(actual: Result.Result<42, never>, message?: string): Assertion<void, Result.Result<42, never>> (+1 overload)
    expect
    (
    const result: Result.Result<42, never>
    result
    ).
    ResultMatchers<void, Result<42, never>>.toBeSuccess: (callback?: ((value: 42) => void) | undefined) => void
    toBeSuccess
    ((
    value: 42
    value
    ) => {
    expect<42>(actual: 42, message?: string): Assertion<void, 42> (+1 overload)
    expect
    (
    value: 42
    value
    ).
    JestAssertion<void, 42>.toBe: <number>(expected: number) => void

    Checks that a value is what you expect. It calls Object.is to compare values. Don't use toBe with floating-point numbers.

    @exampleexpect (result).toBe(42); expect(status).toBe(true);
    toBe
    (42);
    }); });

    コールバックは結果が Success の場合にのみ呼び出され、value には Result の成功型が付きます。

    toBeFailure(callback?)

    受け取った値が Failure であることをアサートします。 コールバックを渡すと、エラー値に対してさらにアサーションを行えます。

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    import {
    const test: TestAPI

    Defines a test case with a given name and test function. The test function can optionally be configured with test options.

    @paramname - The name of the test or a function that will be used as a test name.@paramoptionsOrFn - Optional. The test options or the test function if no explicit name is provided.@paramoptionsOrTest - Optional. The test function or options, depending on the previous parameters.@throws{Error} If called inside another test function.@example
    // Define a simple test
    test('should add two numbers', () => {
      expect(add(1, 2)).toBe(3);
    });
    @example
    // Define a test with options
    test('should subtract two numbers', { retry: 3 }, () => {
      expect(subtract(5, 2)).toBe(3);
    });
    test
    ,
    const expect: ExpectStatic
    expect
    } from 'vitest';
    test<object>(name: string | Function, fn?: TestFunction<object> | undefined, options?: number): void (+1 overload)

    Defines a test case with a given name and test function. The test function can optionally be configured with test options.

    @paramname - The name of the test or a function that will be used as a test name.@paramoptionsOrFn - Optional. The test options or the test function if no explicit name is provided.@paramoptionsOrTest - Optional. The test function or options, depending on the previous parameters.@throws{Error} If called inside another test function.@example
    // Define a simple test
    test('should add two numbers', () => {
      expect(add(1, 2)).toBe(3);
    });
    @example
    // Define a test with options
    test('should subtract two numbers', { retry: 3 }, () => {
      expect(subtract(5, 2)).toBe(3);
    });
    test
    ('result is failure', () => {
    const
    const result: Result.Result<never, Error>
    result
    =
    import Result
    Result
    .
    function fail<Error>(error: Error): Result.Result<never, Error> (+1 overload)

    Creates a Failure result from a given error.

    Passing a Promise is allowed, but it is recommended to await it before passing to fail.

    @typeParamE - The type of the error to wrap.@returnsA Result containing the given error.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail('Something went wrong');
    // Result.Result<never, string>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail();
    // Result.Result<never, void>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    fail
    (new
    var Error: ErrorConstructor
    new (message?: string, options?: ErrorOptions) => Error (+1 overload)
    Error
    ('something went wrong'));
    expect<Result.Result<never, Error>>(actual: Result.Result<never, Error>, message?: string): Assertion<void, Result.Result<never, Error>> (+1 overload)
    expect
    (
    const result: Result.Result<never, Error>
    result
    ).
    ResultMatchers<void, Result<never, Error>>.toBeFailure: (callback?: ((error: Error) => void) | undefined) => void
    toBeFailure
    ();
    });
    test<object>(name: string | Function, fn?: TestFunction<object> | undefined, options?: number): void (+1 overload)

    Defines a test case with a given name and test function. The test function can optionally be configured with test options.

    @paramname - The name of the test or a function that will be used as a test name.@paramoptionsOrFn - Optional. The test options or the test function if no explicit name is provided.@paramoptionsOrTest - Optional. The test function or options, depending on the previous parameters.@throws{Error} If called inside another test function.@example
    // Define a simple test
    test('should add two numbers', () => {
      expect(add(1, 2)).toBe(3);
    });
    @example
    // Define a test with options
    test('should subtract two numbers', { retry: 3 }, () => {
      expect(subtract(5, 2)).toBe(3);
    });
    test
    ('result is failure with error', () => {
    const
    const result: Result.Result<never, Error>
    result
    =
    import Result
    Result
    .
    function fail<Error>(error: Error): Result.Result<never, Error> (+1 overload)

    Creates a Failure result from a given error.

    Passing a Promise is allowed, but it is recommended to await it before passing to fail.

    @typeParamE - The type of the error to wrap.@returnsA Result containing the given error.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail('Something went wrong');
    // Result.Result<never, string>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail();
    // Result.Result<never, void>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    fail
    (new
    var Error: ErrorConstructor
    new (message?: string, options?: ErrorOptions) => Error (+1 overload)
    Error
    ('something went wrong'));
    expect<Result.Result<never, Error>>(actual: Result.Result<never, Error>, message?: string): Assertion<void, Result.Result<never, Error>> (+1 overload)
    expect
    (
    const result: Result.Result<never, Error>
    result
    ).
    ResultMatchers<void, Result<never, Error>>.toBeFailure: (callback?: ((error: Error) => void) | undefined) => void
    toBeFailure
    ((
    error: Error
    error
    ) => {
    expect<string>(actual: string, message?: string): Assertion<void, string> (+1 overload)
    expect
    (
    error: Error
    error
    .
    Error.message: string
    message
    ).
    JestAssertion<void, string>.toBe: <string>(expected: string) => void

    Checks that a value is what you expect. It calls Object.is to compare values. Don't use toBe with floating-point numbers.

    @exampleexpect (result).toBe(42); expect(status).toBe(true);
    toBe
    ('something went wrong');
    }); });

    ヒント

    非同期の Result をテストする

    マッチャーは受け取った値を同期的に検査します。そのため、ResultAsync は await してから expect に渡してください。

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    import {
    const test: TestAPI

    Defines a test case with a given name and test function. The test function can optionally be configured with test options.

    @paramname - The name of the test or a function that will be used as a test name.@paramoptionsOrFn - Optional. The test options or the test function if no explicit name is provided.@paramoptionsOrTest - Optional. The test function or options, depending on the previous parameters.@throws{Error} If called inside another test function.@example
    // Define a simple test
    test('should add two numbers', () => {
      expect(add(1, 2)).toBe(3);
    });
    @example
    // Define a test with options
    test('should subtract two numbers', { retry: 3 }, () => {
      expect(subtract(5, 2)).toBe(3);
    });
    test
    ,
    const expect: ExpectStatic
    expect
    } from 'vitest';
    const
    const fetchAnswer: () => Result.ResultAsync<number, Error>
    fetchAnswer
    = async ():
    import Result
    Result
    .
    type ResultAsync<T, E> = Promise<Result.Result<T, E>>

    An asynchronous variant of Result , wrapped in a Promise.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@example
    import { Result } from '@praha/byethrow';
    
    const fetchData = async (): Result.ResultAsync<string, Error> => {
      try {
        const data = await fetch('...');
        return { type: 'Success', value: await data.text() };
      } catch (err) {
        return { type: 'Failure', error: err as Error };
      }
    };
    @categoryCore Types
    ResultAsync
    <number, Error> =>
    import Result
    Result
    .
    function succeed<42>(value: 42): Result.Result<42, never> (+1 overload)

    Creates a Success result from a given value.

    Passing a Promise is allowed, but it is recommended to await it before passing to succeed.

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed(42);
    // Result.Result<42, never>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed();
    // Result.Result<void, never>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    succeed
    (42);
    test<object>(name: string | Function, fn?: TestFunction<object> | undefined, options?: number): void (+1 overload)

    Defines a test case with a given name and test function. The test function can optionally be configured with test options.

    @paramname - The name of the test or a function that will be used as a test name.@paramoptionsOrFn - Optional. The test options or the test function if no explicit name is provided.@paramoptionsOrTest - Optional. The test function or options, depending on the previous parameters.@throws{Error} If called inside another test function.@example
    // Define a simple test
    test('should add two numbers', () => {
      expect(add(1, 2)).toBe(3);
    });
    @example
    // Define a test with options
    test('should subtract two numbers', { retry: 3 }, () => {
      expect(subtract(5, 2)).toBe(3);
    });
    test
    ('async result is success', async () => {
    const
    const result: Result.Result<number, Error>
    result
    = await
    const fetchAnswer: () => Result.ResultAsync<number, Error>
    fetchAnswer
    ();
    expect<Result.Result<number, Error>>(actual: Result.Result<number, Error>, message?: string): Assertion<void, Result.Result<number, Error>> (+1 overload)
    expect
    (
    const result: Result.Result<number, Error>
    result
    ).
    ResultMatchers<void, Result<number, Error>>.toBeSuccess: (callback?: ((value: number) => void) | undefined) => void
    toBeSuccess
    ((
    value: number
    value
    ) => {
    expect<number>(actual: number, message?: string): Assertion<void, number> (+1 overload)
    expect
    (
    value: number
    value
    ).
    JestAssertion<void, number>.toBe: <number>(expected: number) => void

    Checks that a value is what you expect. It calls Object.is to compare values. Don't use toBe with floating-point numbers.

    @exampleexpect (result).toBe(42); expect(status).toBe(true);
    toBe
    (42);
    }); });

    .not は使わない

    .not.toBeSuccess() と .not.toBeFailure() はサポートされておらず、常に失敗します。 代わりに反対のマッチャーを使ってください。.not.toBeSuccess() ではなく toBeFailure() を、その逆も同様です。

    Linter でマッチャーの使用を徹底する

    prefer-result-matchers の Lint ルールは、expect(Result.isSuccess(result)).toBe(true) のようなアサーションを検出し、これらのマッチャーを使う形に書き換えます。