Перейти к содержимому
GitHubXDiscord

mockCondition

Стабильный · с 0.1.0

Метод TestRuntime, возвращаемого createTestRuntime. Регистрирует условие для триггера, принимая либо статическое значение, либо геттер без аргументов.

mockCondition — тестовый аналог useCondition: тот же механизм регистрации, без React.

import { createTestRuntime } from '@triggery/testing';

const rt = createTestRuntime();
rt.mockCondition(/* ... */);
mockCondition<S extends TriggerSchema, K extends ConditionKey<S>>(
  trigger: Trigger<S>,
  name: K,
  valueOrGetter: ConditionMap<S>[K] | (() => ConditionMap<S>[K]),
): RegistrationToken;
ПараметрТипОписание
triggerTrigger<S>Триггер, чьё условие подменяешь.
nameK extends ConditionKey<S>Условие, объявленное в схеме триггера.
valueOrGetterT | (() => T)Либо статическое значение (захваченное замыканием), либо геттер без аргументов.

RegistrationToken со { unregister(): void }. Вызови unregister(), чтобы сбросить подмена — полезно для смены условий по ходу теста.

import { createTriggerfunction createTrigger<S extends TriggerSchema>(config: CreateTriggerConfig<S>, runtime?: Runtime): Trigger<S>
Create a trigger and register it in a runtime (the default runtime if none is passed).
@example```ts const messageTrigger = createTrigger<{ events: { 'new-message': { author: string; text: string } }; conditions: { user: { id: string }; settings: { sound: boolean } }; actions: { showToast: { title: string }; playSound: void }; }>({ id: 'message-received', events: ['new-message'], required: ['user', 'settings'], handler({ event, conditions, actions, check }) { if (!conditions.user || !conditions.settings) return; // V1: manual narrowing if (check.is('settings', (s) => s.sound)) actions.playSound?.(); actions.showToast?.({ title: event.payload.author }); }, }); ```
} from '@triggery/core';
import { createTestRuntimefunction createTestRuntime(options?: TestRuntimeOptions): TestRuntime } from '@triggery/testing'; const rtconst rt: TestRuntime = createTestRuntimefunction createTestRuntime(options?: TestRuntimeOptions): TestRuntime(); const t
const t: Trigger<{
    events: {
        ping: void;
    };
    conditions: {
        user: {
            id: string;
        } | null;
    };
}>
= createTrigger
createTrigger<{
    events: {
        ping: void;
    };
    conditions: {
        user: {
            id: string;
        } | null;
    };
}>(config: CreateTriggerConfig<{
    events: {
        ping: void;
    };
    conditions: {
        user: {
            id: string;
        } | null;
    };
}>, runtime?: Runtime): Trigger<{
    events: {
        ping: void;
    };
    conditions: {
        user: {
            id: string;
        } | null;
    };
}>
Create a trigger and register it in a runtime (the default runtime if none is passed).
@example```ts const messageTrigger = createTrigger<{ events: { 'new-message': { author: string; text: string } }; conditions: { user: { id: string }; settings: { sound: boolean } }; actions: { showToast: { title: string }; playSound: void }; }>({ id: 'message-received', events: ['new-message'], required: ['user', 'settings'], handler({ event, conditions, actions, check }) { if (!conditions.user || !conditions.settings) return; // V1: manual narrowing if (check.is('settings', (s) => s.sound)) actions.playSound?.(); actions.showToast?.({ title: event.payload.author }); }, }); ```
<{
events
events: {
    ping: void;
}
: { pingping: void: void };
conditions
conditions: {
    user: {
        id: string;
    } | null;
}
: { user
user: {
    id: string;
} | null
: { idid: string: string } | null };
}>( { idid: string: 'demo', eventsevents: readonly "ping"[]: ['ping'], handler
handler: TriggerHandler<{
    events: {
        ping: void;
    };
    conditions: {
        user: {
            id: string;
        } | null;
    };
}, never>
() {},
}, rtconst rt: TestRuntime, ); rtconst rt: TestRuntime.mockCondition
mockCondition<{
    events: {
        ping: void;
    };
    conditions: {
        user: {
            id: string;
        } | null;
    };
}, "user">(trigger: Trigger<{
    events: {
        ping: void;
    };
    conditions: {
        user: {
            id: string;
        } | null;
    };
}>, name: "user", valueOrGetter: {
    id: string;
} | (() => {
    id: string;
} | null) | null): RegistrationToken
Register a condition for a trigger. Accepts either a static value or a zero-argument getter. When the condition's value type is itself a zero-argument function, pass an explicit getter so the runtime knows which one you mean — otherwise the heuristic below would call your value as if it were the getter.
(t
const t: Trigger<{
    events: {
        ping: void;
    };
    conditions: {
        user: {
            id: string;
        } | null;
    };
}>
, 'user', { idid: string: 'u-1' });

Динамический геттер (читать свежий стейт на каждом fire)

Заголовок раздела «Динамический геттер (читать свежий стейт на каждом fire)»
import { createTriggerfunction createTrigger<S extends TriggerSchema>(config: CreateTriggerConfig<S>, runtime?: Runtime): Trigger<S>
Create a trigger and register it in a runtime (the default runtime if none is passed).
@example```ts const messageTrigger = createTrigger<{ events: { 'new-message': { author: string; text: string } }; conditions: { user: { id: string }; settings: { sound: boolean } }; actions: { showToast: { title: string }; playSound: void }; }>({ id: 'message-received', events: ['new-message'], required: ['user', 'settings'], handler({ event, conditions, actions, check }) { if (!conditions.user || !conditions.settings) return; // V1: manual narrowing if (check.is('settings', (s) => s.sound)) actions.playSound?.(); actions.showToast?.({ title: event.payload.author }); }, }); ```
} from '@triggery/core';
import { createTestRuntimefunction createTestRuntime(options?: TestRuntimeOptions): TestRuntime } from '@triggery/testing'; const rtconst rt: TestRuntime = createTestRuntimefunction createTestRuntime(options?: TestRuntimeOptions): TestRuntime(); const t
const t: Trigger<{
    events: {
        tick: void;
    };
    conditions: {
        counter: number;
    };
}>
= createTrigger
createTrigger<{
    events: {
        tick: void;
    };
    conditions: {
        counter: number;
    };
}>(config: CreateTriggerConfig<{
    events: {
        tick: void;
    };
    conditions: {
        counter: number;
    };
}>, runtime?: Runtime): Trigger<{
    events: {
        tick: void;
    };
    conditions: {
        counter: number;
    };
}>
Create a trigger and register it in a runtime (the default runtime if none is passed).
@example```ts const messageTrigger = createTrigger<{ events: { 'new-message': { author: string; text: string } }; conditions: { user: { id: string }; settings: { sound: boolean } }; actions: { showToast: { title: string }; playSound: void }; }>({ id: 'message-received', events: ['new-message'], required: ['user', 'settings'], handler({ event, conditions, actions, check }) { if (!conditions.user || !conditions.settings) return; // V1: manual narrowing if (check.is('settings', (s) => s.sound)) actions.playSound?.(); actions.showToast?.({ title: event.payload.author }); }, }); ```
<{
events
events: {
    tick: void;
}
: { ticktick: void: void };
conditions
conditions: {
    counter: number;
}
: { countercounter: number: number };
}>( { idid: string: 'demo', eventsevents: readonly "tick"[]: ['tick'], handler
handler: TriggerHandler<{
    events: {
        tick: void;
    };
    conditions: {
        counter: number;
    };
}, never>
() {},
}, rtconst rt: TestRuntime, ); let counterlet counter: number = 0; rtconst rt: TestRuntime.mockCondition
mockCondition<{
    events: {
        tick: void;
    };
    conditions: {
        counter: number;
    };
}, "counter">(trigger: Trigger<{
    events: {
        tick: void;
    };
    conditions: {
        counter: number;
    };
}>, name: "counter", valueOrGetter: number | (() => number)): RegistrationToken
Register a condition for a trigger. Accepts either a static value or a zero-argument getter. When the condition's value type is itself a zero-argument function, pass an explicit getter so the runtime knows which one you mean — otherwise the heuristic below would call your value as if it were the getter.
(t
const t: Trigger<{
    events: {
        tick: void;
    };
    conditions: {
        counter: number;
    };
}>
, 'counter', () => counterlet counter: number);
rtconst rt: TestRuntime.fireSyncfunction fireSync(eventName: string, payload?: unknown): void
Run dispatch synchronously (for tests and benchmarks).
('tick'); // handler sees counter=0
counterlet counter: number = 5; rtconst rt: TestRuntime.fireSyncfunction fireSync(eventName: string, payload?: unknown): void
Run dispatch synchronously (for tests and benchmarks).
('tick'); // handler sees counter=5
import { createTriggerfunction createTrigger<S extends TriggerSchema>(config: CreateTriggerConfig<S>, runtime?: Runtime): Trigger<S>
Create a trigger and register it in a runtime (the default runtime if none is passed).
@example```ts const messageTrigger = createTrigger<{ events: { 'new-message': { author: string; text: string } }; conditions: { user: { id: string }; settings: { sound: boolean } }; actions: { showToast: { title: string }; playSound: void }; }>({ id: 'message-received', events: ['new-message'], required: ['user', 'settings'], handler({ event, conditions, actions, check }) { if (!conditions.user || !conditions.settings) return; // V1: manual narrowing if (check.is('settings', (s) => s.sound)) actions.playSound?.(); actions.showToast?.({ title: event.payload.author }); }, }); ```
} from '@triggery/core';
import { createTestRuntimefunction createTestRuntime(options?: TestRuntimeOptions): TestRuntime } from '@triggery/testing'; const rtconst rt: TestRuntime = createTestRuntimefunction createTestRuntime(options?: TestRuntimeOptions): TestRuntime(); const t
const t: Trigger<{
    events: {
        ping: void;
    };
    conditions: {
        flag: boolean;
    };
}>
= createTrigger
createTrigger<{
    events: {
        ping: void;
    };
    conditions: {
        flag: boolean;
    };
}>(config: CreateTriggerConfig<{
    events: {
        ping: void;
    };
    conditions: {
        flag: boolean;
    };
}>, runtime?: Runtime): Trigger<{
    events: {
        ping: void;
    };
    conditions: {
        flag: boolean;
    };
}>
Create a trigger and register it in a runtime (the default runtime if none is passed).
@example```ts const messageTrigger = createTrigger<{ events: { 'new-message': { author: string; text: string } }; conditions: { user: { id: string }; settings: { sound: boolean } }; actions: { showToast: { title: string }; playSound: void }; }>({ id: 'message-received', events: ['new-message'], required: ['user', 'settings'], handler({ event, conditions, actions, check }) { if (!conditions.user || !conditions.settings) return; // V1: manual narrowing if (check.is('settings', (s) => s.sound)) actions.playSound?.(); actions.showToast?.({ title: event.payload.author }); }, }); ```
<{
events
events: {
    ping: void;
}
: { pingping: void: void };
conditions
conditions: {
    flag: boolean;
}
: { flagflag: boolean: boolean };
}>( { idid: string: 'demo', eventsevents: readonly "ping"[]: ['ping'], handler
handler: TriggerHandler<{
    events: {
        ping: void;
    };
    conditions: {
        flag: boolean;
    };
}, never>
() {} },
rtconst rt: TestRuntime, ); const offconst off: RegistrationToken = rtconst rt: TestRuntime.mockCondition
mockCondition<{
    events: {
        ping: void;
    };
    conditions: {
        flag: boolean;
    };
}, "flag">(trigger: Trigger<{
    events: {
        ping: void;
    };
    conditions: {
        flag: boolean;
    };
}>, name: "flag", valueOrGetter: boolean | (() => boolean)): RegistrationToken
Register a condition for a trigger. Accepts either a static value or a zero-argument getter. When the condition's value type is itself a zero-argument function, pass an explicit getter so the runtime knows which one you mean — otherwise the heuristic below would call your value as if it were the getter.
(t
const t: Trigger<{
    events: {
        ping: void;
    };
    conditions: {
        flag: boolean;
    };
}>
, 'flag', true);
rtconst rt: TestRuntime.fireSyncfunction fireSync(eventName: string, payload?: unknown): void
Run dispatch synchronously (for tests and benchmarks).
('ping'); // handler sees flag=true
offconst off: RegistrationToken.unregisterfunction unregister(): void
Idempotent unregister.
();
rtconst rt: TestRuntime.mockCondition
mockCondition<{
    events: {
        ping: void;
    };
    conditions: {
        flag: boolean;
    };
}, "flag">(trigger: Trigger<{
    events: {
        ping: void;
    };
    conditions: {
        flag: boolean;
    };
}>, name: "flag", valueOrGetter: boolean | (() => boolean)): RegistrationToken
Register a condition for a trigger. Accepts either a static value or a zero-argument getter. When the condition's value type is itself a zero-argument function, pass an explicit getter so the runtime knows which one you mean — otherwise the heuristic below would call your value as if it were the getter.
(t
const t: Trigger<{
    events: {
        ping: void;
    };
    conditions: {
        flag: boolean;
    };
}>
, 'flag', false);
rtconst rt: TestRuntime.fireSyncfunction fireSync(eventName: string, payload?: unknown): void
Run dispatch synchronously (for tests and benchmarks).
('ping'); // handler sees flag=false

Условие с функциональным типом требует явный геттер

Заголовок раздела «Условие с функциональным типом требует явный геттер»

Когда значение условия — это функция без аргументов, эвристика может ошибочно принять её за геттер. Передавай явный геттер:

import { createTriggerfunction createTrigger<S extends TriggerSchema>(config: CreateTriggerConfig<S>, runtime?: Runtime): Trigger<S>
Create a trigger and register it in a runtime (the default runtime if none is passed).
@example```ts const messageTrigger = createTrigger<{ events: { 'new-message': { author: string; text: string } }; conditions: { user: { id: string }; settings: { sound: boolean } }; actions: { showToast: { title: string }; playSound: void }; }>({ id: 'message-received', events: ['new-message'], required: ['user', 'settings'], handler({ event, conditions, actions, check }) { if (!conditions.user || !conditions.settings) return; // V1: manual narrowing if (check.is('settings', (s) => s.sound)) actions.playSound?.(); actions.showToast?.({ title: event.payload.author }); }, }); ```
} from '@triggery/core';
import { createTestRuntimefunction createTestRuntime(options?: TestRuntimeOptions): TestRuntime } from '@triggery/testing'; const rtconst rt: TestRuntime = createTestRuntimefunction createTestRuntime(options?: TestRuntimeOptions): TestRuntime(); type Callbacktype Callback = () => void = () => void; const t
const t: Trigger<{
    events: {
        ping: void;
    };
    conditions: {
        onTick: Callback;
    };
}>
= createTrigger
createTrigger<{
    events: {
        ping: void;
    };
    conditions: {
        onTick: Callback;
    };
}>(config: CreateTriggerConfig<{
    events: {
        ping: void;
    };
    conditions: {
        onTick: Callback;
    };
}>, runtime?: Runtime): Trigger<{
    events: {
        ping: void;
    };
    conditions: {
        onTick: Callback;
    };
}>
Create a trigger and register it in a runtime (the default runtime if none is passed).
@example```ts const messageTrigger = createTrigger<{ events: { 'new-message': { author: string; text: string } }; conditions: { user: { id: string }; settings: { sound: boolean } }; actions: { showToast: { title: string }; playSound: void }; }>({ id: 'message-received', events: ['new-message'], required: ['user', 'settings'], handler({ event, conditions, actions, check }) { if (!conditions.user || !conditions.settings) return; // V1: manual narrowing if (check.is('settings', (s) => s.sound)) actions.playSound?.(); actions.showToast?.({ title: event.payload.author }); }, }); ```
<{
events
events: {
    ping: void;
}
: { pingping: void: void };
conditions
conditions: {
    onTick: Callback;
}
: { onTickonTick: Callback: Callbacktype Callback = () => void };
}>( { idid: string: 'demo', eventsevents: readonly "ping"[]: ['ping'], handler
handler: TriggerHandler<{
    events: {
        ping: void;
    };
    conditions: {
        onTick: Callback;
    };
}, never>
() {} },
rtconst rt: TestRuntime, ); const cbconst cb: Callback: Callbacktype Callback = () => void = () => consolevar console: Console.logConsole.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
('tick');
// Wrap in a getter so the runtime stores `cb`, not the result of calling cb. rtconst rt: TestRuntime.mockCondition
mockCondition<{
    events: {
        ping: void;
    };
    conditions: {
        onTick: Callback;
    };
}, "onTick">(trigger: Trigger<{
    events: {
        ping: void;
    };
    conditions: {
        onTick: Callback;
    };
}>, name: "onTick", valueOrGetter: Callback | (() => Callback)): RegistrationToken
Register a condition for a trigger. Accepts either a static value or a zero-argument getter. When the condition's value type is itself a zero-argument function, pass an explicit getter so the runtime knows which one you mean — otherwise the heuristic below would call your value as if it were the getter.
(t
const t: Trigger<{
    events: {
        ping: void;
    };
    conditions: {
        onTick: Callback;
    };
}>
, 'onTick', () => cbconst cb: Callback);