### Install XState and XState Test Packages
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/model-based-testing/quickstart
Instructions to install the necessary XState and @xstate/test packages using Yarn for model-based testing.
```bash
yarn add xstate @xstate/test@alpha
```
--------------------------------
### Install XState and XState Test Libraries
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-test
Instructions to install the necessary npm packages for XState machine testing.
```shell
npm install xstate @xstate/test
```
--------------------------------
### Pseudocode Example: Setup and Assert for Database User Addition
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/model-based-testing/assertions
Demonstrates the fundamental 'setup, then assert' testing pattern using pseudocode. It illustrates clearing a database as the setup phase and then verifying user existence as the assertion phase for a addUserToDb function.
```Pseudocode
describe('addUserToDb', () => {
it('Should add a user to a database', async () => {
// SETUP
// Clear the database before each test
await testUtils.clearDatabase();
// Run the function we’re testing
await addUserToDb({
name: 'Matt',
});
// ASSERT
// Ensure that the user exists
await testUtils.ensureUserExistsInDb({
name: 'Matt',
});
});
});
```
--------------------------------
### Install XState and Graph Utilities
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-graph
Instructions to install the necessary XState and @xstate/graph packages using npm, which are required to use the graph utilities.
```npm
npm install xstate @xstate/graph
```
--------------------------------
### Create a Test Machine with createTestMachine
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/model-based-testing/quickstart
Defines a state machine for testing purposes using `createTestMachine`, outlining states and transitions for a search flow example. This machine will be used to generate test paths.
```javascript
import { createTestMachine } from '@xstate/test';
const machine = createTestMachine({
initial: 'onHomePage',
states: {
onHomePage: {
on: {
SEARCH_FOR_MODEL_BASED_TESTING: 'searchResultsVisible',
},
},
searchResultsVisible: {
on: {
CLICK_MODEL_BASED_TESTING_RESULT: 'onModelBasedTestingPage',
PRESS_ESCAPE: 'searchBoxClosed',
},
},
searchBoxClosed: {},
onModelBasedTestingPage: {},
},
});
```
--------------------------------
### Example of getSimplePaths Usage with XState
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-graph
This JavaScript example demonstrates how to define an XState machine and then use `getSimplePaths` from `@xstate/graph` to compute and log all simple paths within that machine. The expected output structure is also shown.
```javascript
import { createMachine } from 'xstate';
import { getSimplePaths } from '@xstate/graph';
const feedbackMachine = createMachine({
id: 'feedback',
initial: 'question',
states: {
question: {
on: {
CLICK_GOOD: 'thanks',
CLICK_BAD: 'form',
CLOSE: 'closed',
ESC: 'closed',
},
},
form: {
on: {
SUBMIT: 'thanks',
CLOSE: 'closed',
ESC: 'closed',
},
},
thanks: {
on: {
CLOSE: 'closed',
ESC: 'closed',
},
},
closed: {
type: 'final',
},
},
});
const simplePaths = getSimplePaths(feedbackMachine);
console.log(simplePaths);
// => {
// '"question"': {
// state: { value: 'question', context: undefined },
// paths: [[]]
// },
// '"thanks"': {
// state: { value: 'thanks', context: undefined },
// paths: [
// [
// {
// state: { value: 'question', context: undefined },
// event: { type: 'CLICK_GOOD' }
// }
// ],
// [
// {
// state: { value: 'question', context: undefined },
// event: { type: 'CLICK_BAD' }
// },
// {
// state: { value: 'form', context: undefined },
// event: { type: 'SUBMIT' }
// }
// ]
// ]
// },
// '"closed"': {
// state: { value: 'closed', context: undefined },
// paths: [
// [
// {
// state: { value: 'question', context: undefined },
// event: { type: 'CLICK_GOOD' }
// },
// {
// state: { value: 'thanks', context: undefined },
// event: { type: 'CLOSE' }
// }
// ],
// [
// {
// state: { value: 'question', context: undefined },
// event: { type: 'CLICK_GOOD' }
// },
// {
// state: { value: 'thanks', context: undefined },
// event: { type: 'ESC' }
// }
// ],
// ...
// ]
// },
// ...
// };
```
--------------------------------
### Install XState and Svelte Integration Packages
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-svelte
This snippet shows how to install the `xstate` and `@xstate/svelte` packages using npm, which are essential for state management in Svelte applications.
```npm
npm i xstate @xstate/svelte
```
--------------------------------
### Import and Use XState Graph Utilities
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-graph
Demonstrates how to import `createMachine` from xstate and `getSimplePaths` from @xstate/graph, then use them to get simple paths of a machine.
```javascript
import { createMachine } from 'xstate';
import { getSimplePaths } from '@xstate/graph';
const machine = createMachine(/* ... */);
const paths = getSimplePaths(machine);
```
--------------------------------
### Install XState Immer Dependencies
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-immer
This snippet provides the command to install the necessary peer dependencies for `@xstate/immer`, including `immer`, `xstate`, and `@xstate/immer` itself, using npm.
```shell
npm install immer xstate @xstate/immer
```
--------------------------------
### Implement XState Machine Actions with Options
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/basics/options
This example shows how to provide implementation details for an XState machine's actions using the 'options' object. It defines the 'sayHello' action, demonstrating a simple synchronous operation executed when the machine starts.
```javascript
const helloMachine = createMachine(
{
entry: ['sayHello'],
},
{
actions: {
sayHello: () => {
console.log('Hello!');
},
},
},
);
```
--------------------------------
### XState FSM Machine Integration in Svelte (Fetch Example)
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-svelte
This example demonstrates using the `useMachine` hook from `@xstate/svelte/lib/fsm` to integrate a finite state machine for a data fetching scenario. It showcases machine creation with context and actions, and how to update the component based on the machine's state.
```html
{#if $state.value === 'idle'}
{:else if $state.value === 'loading'}
Loading...
{:else if $state.value === 'success'}
Success! Data:
{$state.context.data}
{/if}
```
--------------------------------
### XState Test Setup During a Test via Events
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/model-based-testing/assertions
Illustrates how to perform test setup dynamically during a test by providing event implementations to path.testSync(). This example uses a CLICK event to simulate user interaction and transition the machine state, demonstrating how the test model uses these implementations for setup.
```JavaScript
const machine = createTestMachine({
initial: 'buttonIsPending',
states: {
buttonIsPending: {
on: {
CLICK: 'buttonIsComplete',
},
},
buttonIsComplete: {},
},
});
createTestModel(machine)
.getPaths()
.forEach((path) => {
it(path.description, () => {
path.testSync({
events: {
CLICK: () => {
cy.findByRole('button').click();
},
},
});
});
});
```
--------------------------------
### Install XState and XState Vue Packages
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-vue
This command installs the necessary `xstate` and `@xstate/vue` packages using npm, which are required to use XState with Vue.js.
```npm
npm i xstate @xstate/vue
```
--------------------------------
### Example: Using getShortestPaths with a Feedback Machine
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-graph
Illustrates how to define a feedback state machine using `createMachine` and then apply `getShortestPaths` to calculate the shortest paths from its initial state to all other reachable states, showing the expected output structure.
```javascript
import { createMachine } from 'xstate';
import { getShortestPaths } from '@xstate/graph';
const feedbackMachine = createMachine({
id: 'feedback',
initial: 'question',
states: {
question: {
on: {
CLICK_GOOD: 'thanks',
CLICK_BAD: 'form',
CLOSE: 'closed',
ESC: 'closed',
},
},
form: {
on: {
SUBMIT: 'thanks',
CLOSE: 'closed',
ESC: 'closed',
},
},
thanks: {
on: {
CLOSE: 'closed',
ESC: 'closed',
},
},
closed: {
type: 'final',
},
},
});
const shortestPaths = getShortestPaths(feedbackMachine);
console.log(shortestPaths);
// => {
// '"question"': {
// state: State { value: 'question', context: undefined },
// weight: 0,
// path: []
// },
// '"thanks"': {
// state: State { value: 'thanks', context: undefined },
// weight: 1,
// path: [
// {
// state: State { value: 'question', context: undefined },
// event: { type: 'CLICK_GOOD' }
// }
// ]
// },
// '"form"': {
// state: State { value: 'form', context: undefined },
// weight: 1,
// path: [
// {
// state: State { value: 'question', context: undefined },
// event: { type: 'CLICK_BAD' }
// }
// ]
// },
// '"closed"': {
// state: State { value: 'closed', context: undefined },
// weight: 1,
// path: [
// {
// state: State { value: 'question', context: undefined },
// event: { type: 'CLOSE' }
// }
// ]
// }
// };
```
--------------------------------
### Install XState and @xstate/react
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-react
This command installs the `xstate` core library and the `@xstate/react` package, which provides React-specific utilities for XState.
```bash
npm i xstate @xstate/react
```
--------------------------------
### Access XState Global Exports after CDN Load
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/installation
This JavaScript example shows how to destructure and access core XState functions like `createMachine`, `actions`, and `interpret` from the globally available `XState` object after the library has been loaded via CDN. It then demonstrates basic usage by creating and interpreting a machine.
```JavaScript
const { createMachine, actions, interpret } = XState; // global variable: window.XState
const lightMachine = createMachine({
// ...
});
const lightActor = interpret(lightMachine);
```
--------------------------------
### Example XState Machine Definition for Import
Source: https://stately.ai/docs/xstate-v4/xstate/import-from-code
This code snippet presents a valid `createMachine()` factory function, ready for import into the Stately editor. It defines a 'Video' state machine with states for 'Closed' and 'Opened' (which includes nested 'Playing', 'Paused', and 'Stopped' states), demonstrating state transitions, actions, and initial states. This example can be directly imported without errors.
```JavaScript
createMachine({
id: 'Video',
initial: 'Closed',
description: 'Video player',
states: {
Closed: {
on: {
PLAY: {
target: 'Opened'
}
}
},
Opened: {
invoke: {
src: 'startVideo'
},
initial: 'Playing',
description: 'Fullscreen mode',
states: {
Playing: {
on: {
PAUSE: {
target: 'Paused'
}
}
},
Paused: {
on: {
PLAY: {
target: 'Playing'
}
}
},
Stopped: {
type: 'final',
after: {
5000: {
target: '#Video.Closed',
actions: [],
internal: false
}
}
}
},
on: {
STOP: {
target: '.Stopped'
}
}
}
},
context: {},
predictableActionArguments: true,
preserveActionOrder: true
});
```
--------------------------------
### Install XState v4 using Package Managers
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/installation
Commands to install the XState v4 library using either Yarn or npm. Note that XState v4 is no longer actively maintained and users are encouraged to migrate to XState v5.
```bash
yarn add xstate
```
```bash
npm install xstate
```
--------------------------------
### Turn a Machine into a Test Model with createTestModel
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/model-based-testing/quickstart
Converts the previously defined test machine into a test model using `createTestModel`. This model is essential for generating and running test paths based on the machine's logic.
```javascript
import { createTestModel } from '@xstate/test';
const model = createTestModel(machine);
```
--------------------------------
### Basic XState Machine Integration in Svelte
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-svelte
This example demonstrates how to import and use the `useMachine` hook from `@xstate/svelte` to integrate a simple toggle state machine into a Svelte component. It shows how to define a machine, interpret it, and interact with its state and send events.
```html
```
--------------------------------
### Install XState FSM Package
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-fsm
This snippet demonstrates how to install the `@xstate/fsm` package using npm, a package manager for JavaScript. It's the first step to integrate the finite state machine library into your project.
```npm
npm i @xstate/fsm
```
--------------------------------
### API Reference: useMachine(machine, options?)
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-vue
Documentation for the `useMachine` Vue composition function, which interprets an XState machine and starts a service for the component's lifetime. It details arguments, return values, and their types.
```APIDOC
useMachine(machine, options?): { state, send, service }
machine: An XState machine.
options (optional): Interpreter options OR Machine Config options (guards, actions, activities, services, delays, immediate, context, state).
Returns:
state: Current state of the machine as an XState State object.
send: Function that sends events to the running service.
service: The created service.
```
--------------------------------
### useMachine Hook API Reference
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-react
Documentation for the `useMachine` React hook, which interprets a given XState machine and starts a service for the component's lifetime. It details the arguments, return values, and provides examples for both existing and lazily-created machines.
```APIDOC
useMachine(machine: XStateMachine | () => XStateMachine, options?: InterpreterOptions | MachineConfigOptions): [State, SendFunction, Service]
Arguments:
machine: An XState machine or a function that lazily returns a machine.
Example (existing machine):
const [state, send] = useMachine(machine);
Example (lazily-created machine):
const [state, send] = useMachine(() =>
createMachine({ /* ... */ }),
);
options (optional): Interpreter options and/or any of the following machine config options: guards, actions, services, delays, immediate, context, state. If the machine already contains any of these options, they will be merged, with these options taking precedence.
Returns:
state: Represents the current state of the machine as an XState `State` object.
send: A function that sends events to the running service.
service: The created service.
```
--------------------------------
### Example: Using `assign` for Nested Context Updates
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-immer
This example illustrates how to use the `assign` utility from `@xstate/immer` to immutably update nested properties within an XState machine's context. It demonstrates updating an `address.country` property based on an event.
```javascript
import { createMachine } from 'xstate';
import { assign } from '@xstate/immer';
const userMachine = createMachine({
id: 'user',
context: {
name: null,
address: {
city: null,
state: null,
country: null,
},
},
initial: 'active',
states: {
active: {
on: {
CHANGE_COUNTRY: {
actions: assign((context, event) => {
context.address.country = event.value;
}),
},
},
},
},
});
const { initialState } = userMachine;
const nextState = userMachine.transition(initialState, {
type: 'UPDATE_COUNTRY',
country: 'USA',
});
nextState.context.address.country;
// => 'USA'
```
--------------------------------
### Configuring XState Machines in Vue
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-vue
Demonstrates how to configure existing XState machines in Vue applications by passing options as the second argument to `useMachine(machine, options)`. This example shows how to configure `fetchData` service and `notifySuccess` action.
```vue
Searching...
Success! {{ state.context.data }}
{{ state.context.error.message }}
```
--------------------------------
### Specify XState Machine Options with .withConfig
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/basics/options
This example demonstrates how to apply machine options dynamically after machine creation using the `.withConfig` method. This allows for flexible option definition separate from the initial machine configuration.
```javascript
import { createMachine } from 'xstate';
const machine = createMachine({});
// ---cut---
machine.withConfig({
actions: {},
// `actors` in v5
services: {},
guards: {},
delays: {},
});
```
--------------------------------
### Basic useInterpret Hook in Vue
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-vue
Demonstrates the fundamental usage of the `useInterpret` composition function to interpret an XState machine within a Vue component's `setup` function, returning the service.
```Vue.js
import { useInterpret } from '@xstate/vue';
import { someMachine } from '../path/to/someMachine';
export default {
setup() {
const service = useInterpret(someMachine);
return service;
},
};
```
--------------------------------
### Install XState and React Integration Package
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/running-machines/react
Instructions to install the `xstate` core library and the `@xstate/react` package using npm, which are essential for integrating XState state machines into React applications.
```Shell
npm install xstate @xstate/react
```
--------------------------------
### XState Machine with Wildcard Transition Example
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/states/parent-and-child-states
This XState machine example illustrates the behavior of wildcard transitions (`*`) in conjunction with specific event handlers. It shows how the wildcard catches unhandled events at the machine level, while more specific `on` handlers at the machine or state level take precedence, demonstrating when the wildcard is triggered or ignored based on the current state and event specificity.
```javascript
import { createMachine } from 'xstate';
const machine = createMachine({
initial: 'inactive',
on: {
'*': {
actions: 'logEventToConsole',
},
FOCUS: {
actions: 'onFocus',
},
},
states: {
inactive: {
on: {
HOVER: {
actions: 'onHover',
},
},
},
active: {},
},
});
```
--------------------------------
### Using XState Services as Svelte Stores
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-svelte
This example illustrates how XState services implement the Svelte store contract, allowing direct access and automatic subscriptions. It shows a `toggleMachine` defined in `service.js` and how its `toggleService` is imported and used in `App.svelte` to control button text based on the service's current state.
```javascript
// service.js
import { createMachine, interpret } from 'xstate';
const toggleMachine = createMachine({
id: 'toggle',
initial: 'inactive',
states: {
inactive: {
on: { TOGGLE: 'active' },
},
active: {
on: { TOGGLE: 'inactive' },
},
},
});
export const toggleService = interpret(toggleMachine).start();
```
```svelte
// App.svelte
```
--------------------------------
### Define XState Toggle Machine
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-test
Illustrates how to create a basic XState machine with 'inactive' and 'active' states and a 'TOGGLE' event.
```javascript
import { createMachine } from 'xstate';
const toggleMachine = createMachine({
id: 'toggle',
initial: 'inactive',
states: {
inactive: {
on: {
TOGGLE: 'active',
},
},
active: {
on: {
TOGGLE: 'inactive',
},
},
},
});
```
--------------------------------
### Implement XState Machine with Immer `assign` and `createUpdater`
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-immer
This example demonstrates how to integrate `@xstate/immer` utilities, `assign` and `createUpdater`, into an XState machine. It shows immutable context updates for a `count` property using `assign` and a `level` property using `createUpdater` within a toggle machine, illustrating state transitions and context changes.
```javascript
import { createMachine, interpret } from 'xstate';
import { assign, createUpdater } from '@xstate/immer';
const levelUpdater = createUpdater('UPDATE_LEVEL', (ctx, { input }) => {
ctx.level = input;
});
const toggleMachine = createMachine({
id: 'toggle',
context: {
count: 0,
level: 0,
},
initial: 'inactive',
states: {
inactive: {
on: {
TOGGLE: {
target: 'active',
// Immutably update context the same "mutable"
// way as you would do with Immer!
actions: assign((ctx) => ctx.count++),
},
},
},
active: {
on: {
TOGGLE: {
target: 'inactive',
},
// Use the updater for more convenience:
[levelUpdater.type]: {
actions: levelUpdater.action,
},
},
},
},
});
const toggleService = interpret(toggleMachine)
.onTransition((state) => {
console.log(state.context);
})
.start();
toggleService.send('TOGGLE');
// { count: 1, level: 0 }
toggleService.send(levelUpdater.update(9));
// { count: 1, level: 9 }
toggleService.send('TOGGLE');
// { count: 2, level: 9 }
toggleService.send(levelUpdater.update(-100));
// Notice how the level is not updated in 'inactive' state:
// { count: 2, level: 9 }
```
--------------------------------
### useInterpret with Options and State Listener
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-vue
Illustrates how to use `useInterpret` with additional configuration options (e.g., `actions`) and a listener function to subscribe to and log state changes, providing dynamic interaction with the machine.
```Vue.js
import { useInterpret } from '@xstate/vue';
import { someMachine } from '../path/to/someMachine';
export default {
setup() {
const service = useInterpret(
someMachine,
{
actions: {
/* ... */
},
},
(state) => {
// subscribes to state changes
console.log(state.value);
},
);
// ...
},
};
```
--------------------------------
### XState TestModel: Get Plan From Events
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-test
Generates a single testing plan with a single path based on a sequence of events. Throws an error if the final state does not match the target option.
```APIDOC
testModel.getPlanFromEvents(events, options)
events: EventObject[] - The sequence of events to create the plan
options: { target: string } - An object with a `target` property that should match the target state of the events
Returns: array - An array with a single testing plan with a single path generated from the events.
```
--------------------------------
### Create XState Test Model with Events
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-test
Shows how to create a test model from an XState machine using `@xstate/test`'s `createModel` and define event execution logic with `withEvents`.
```javascript
import { createMachine } from 'xstate';
import { createModel } from '@xstate/test';
const toggleMachine = createMachine(/* ... */);
const toggleModel = createModel(toggleMachine).withEvents({
TOGGLE: {
exec: async (page) => {
await page.click('input');
},
},
});
```
--------------------------------
### Fully Typed XState Form Machine with createUpdater (TypeScript)
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-immer
Provides a comprehensive example of an XState machine for a form, demonstrating the full type-safety integration of `createUpdater` and `ImmerUpdateEvent`. It defines context and event interfaces, creates typed updaters, and configures the machine with a schema for type inference.
```typescript
import { createMachine } from 'xstate';
import { createUpdater, ImmerUpdateEvent } from '@xstate/immer';
interface FormContext {
name: string;
age: number | undefined;
}
type NameUpdateEvent = ImmerUpdateEvent<'UPDATE_NAME', string>;
type AgeUpdateEvent = ImmerUpdateEvent<'UPDATE_AGE', number>;
const nameUpdater = createUpdater(
'UPDATE_NAME',
(ctx, { input }) => {
ctx.name = input;
},
);
const ageUpdater = createUpdater(
'UPDATE_AGE',
(ctx, { input }) => {
ctx.age = input;
},
);
type FormEvent =
| NameUpdateEvent
| AgeUpdateEvent
| {
type: 'SUBMIT';
};
const formMachine = createMachine({
schema: {
context: {} as FormContext,
events: {} as FormEvent,
},
initial: 'editing',
context: {
name: '',
age: undefined,
},
states: {
editing: {
on: {
[nameUpdater.type]: { actions: nameUpdater.action },
[ageUpdater.type]: { actions: ageUpdater.action },
SUBMIT: 'submitting',
},
},
submitting: {
// ...
},
},
});
```
--------------------------------
### Example of a Condensed Test Path
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/model-based-testing/test-paths
This snippet illustrates the single, condensed test path generated by the `@xstate/test` model for the `loginMachine` defined previously. It shows a sequence of state transitions that covers multiple behaviors efficiently.
```text
showingLoginForm
-> SUBMIT_VALID_FORM -> loggedIn
-> LOG_OUT -> showingLoginForm
-> SUBMIT_INVALID_FORM -> passwordInvalid
```
--------------------------------
### API Reference: createModel Function
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-test
Creates an abstract testing model from an XState machine. It takes the machine and optional configuration.
```APIDOC
createModel(machine, options?)
machine: StateMachine - The machine used to create the abstract model.
options?: TestModelOptions - Options to customize the abstract model.
Returns: TestModel instance.
```
--------------------------------
### XState Test Setup Before Each Path
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/model-based-testing/assertions
Shows how to integrate test setup logic that needs to run before each generated test path in an XState model-based test. The setup code is placed within the it block, prior to calling path.testSync().
```JavaScript
const paths = model.getPaths();
describe('My model', () => {
paths.forEach((path) => {
it(path.description, () => {
/**
* Run any setup that needs to happen
* before each test
*/
// Run the test
path.testSync({
states: {},
events: {},
});
/**
* Run any teardown that needs to
* happen after each test
*/
});
});
});
```
--------------------------------
### Example GitHub URL Transformation for Stately Studio
Source: https://stately.ai/docs/xstate-v4/xstate/import-from-github
Demonstrates how to modify a standard GitHub file URL to trigger an import into Stately Studio. Replace '.com' with '.stately.ai' in the URL.
```text
Original: https://github.com/username/repo/blob/main/apps/superMachine.ts
Transformed: https://github.stately.ai/username/repo/blob/main/apps/superMachine.ts
```
--------------------------------
### XState Service: Start Interpreted Machine
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-fsm
Starts the interpreted machine service. Events will only trigger transitions after the service has started. All subscribed listeners will receive the machine's initial state upon start.
```APIDOC
service.start(): Starts the interpreted machine.
Events sent to the interpreted machine will not trigger any transitions until the service is started. All listeners (via service.subscribe(listener)) will receive the machine.initialState.
```
--------------------------------
### Install XState CLI Package
Source: https://stately.ai/docs/xstate-v4/xstate/tools/developer-tools
Installs the @xstate/cli package using npm, which provides command-line interface tools for XState, including type generation. This package is part of the XState tools repository.
```Shell
npm install @xstate/cli
```
--------------------------------
### Migrating XState Vue from 0.4.0: useService to useActor
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-vue
Provides a migration guide for XState Vue users upgrading from version 0.4.0, specifically detailing the change from `useService()` to `useActor()` for spawned actors.
```javascript
-import { useService } from '@xstate/vue';
+import { useActor } from '@xstate/vue';
-const {state, send} = useService(someActor);
+const {state, send} = useActor(someActor);
```
--------------------------------
### XState TestPlan: Description Property
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-test
A string property providing a description of the testing plan, detailing the goal of reaching the `testPlan.state`.
```APIDOC
testPlan.description: string - The string description of the testing plan, describing the goal of reaching the `testPlan.state`.
```
--------------------------------
### Calculate Shortest Paths for XState Counter Machine with Event Expansion
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-graph
This JavaScript example demonstrates how to use `getShortestPaths` with an XState counter machine. It shows how to expand the `INC` event to include multiple payload values (1 and 2) and how to use a `filter` function to limit the state space, preventing infinite loops by ensuring `state.context.count` does not exceed 5. The output displays the calculated shortest paths from the initial state.
```javascript
const counterMachine = createMachine({
id: 'counter',
initial: 'active',
context: { count: 0 },
states: {
active: {
on: {
INC: {
actions: assign({ count: (ctx, e) => ctx.count + e.value }),
},
},
},
},
});
const shortestPaths = getShortestPaths(counterMachine, {
events: {
INC: [
{ type: 'INC', value: 1 },
{ type: 'INC', value: 2 },
],
},
filter: (state) => state.context.count <= 5,
});
console.log(shortestPaths);
// => {
// '"active" | {"count":0}': {
// state: { value: 'active', context: { count: 0 } },
// weight: 0,
// path: []
// },
// '"active" | {"count":1}': {
// state: { value: 'active', context: { count: 1 } },
// weight: 1,
// path: [
// {
// state: { value: 'active', context: { count: 0 } },
// event: { type: 'INC', value: 1 }
// }
// ]
// },
// '"active" | {"count":2}': {
// state: { value: 'active', context: { count: 2 } },
// weight: 1,
// path: [
// {
// state: { value: 'active', context: { count: 0 } },
// event: { type: 'INC', value: 2 }
// }
// ]
// },
// '"active" | {"count":3}': {
// state: { value: 'active', context: { count: 3 } },
// weight: 2,
// path: [
// {
// state: { value: 'active', context: { count: 0 } },
// event: { type: 'INC', value: 1 }
// },
// {
// state: { value: 'active', context: { count: 1 } },
// event: { type: 'INC', value: 2 }
// }
// ]
// },
// ...
// };
```
--------------------------------
### Embed XState via CDN Script Tag
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/installation
This HTML snippet demonstrates how to include the XState library in a web page directly from the unpkg CDN using a script tag. This makes the `XState` global variable available for use in subsequent scripts.
```HTML
```
--------------------------------
### Interpreting a Basic XState Machine
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/running-machines/intro
This snippet demonstrates the fundamental use of `interpret` to create a running instance of an XState machine, referred to as an 'actor'. The `start()` method initiates the machine, making it interactive.
```javascript
import { createMachine, interpret } from 'xstate';
const machine = createMachine({});
const actor = interpret(machine).start();
```
--------------------------------
### XState TestPath: Description Property
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-test
A string property providing a description of the testing path, detailing a sequence of events that will reach the `testPath.state`.
```APIDOC
testPath.description: string - The string description of the testing path, describing a sequence of events that will reach the `testPath.state`.
```
--------------------------------
### Run XState Test Model with Cypress
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/model-based-testing/quickstart
Demonstrates how to integrate and run the XState test model within a Cypress test suite. It iterates through generated paths and defines actions for specific states and events using Cypress commands to simulate user interactions and assert UI states.
```javascript
describe('Toggle component', () => {
/**
* For each path generated by XState,
* run a new test via `it`
*/
model.getPaths().forEach((path) => {
it(path.description, () => {
// Run any setup before each test here
/**
* In environments, like Cypress,
* that don’t support async, run plan.testSync();
*
* Otherwise, you can run await plan.test();
*/
path.testSync({
states: {
onHomePage: () => {
cy.visit('/');
},
searchResultsVisible: () => {
cy.findByText('Model-based testing').should('be.visible');
},
searchBoxClosed: () => {
cy.findByText('Model-based testing').should('not.be.visible');
},
onModelBasedTestingPage: () => {
cy.url().should('include', '/model-based-testing/intro');
}
},
events: {
CLICK_MODEL_BASED_TESTING_RESULT: () => {
cy.findByText('Model-based testing').click();
},
SEARCH_FOR_MODEL_BASED_TESTING: () => {
cy.findByPlaceholderText('Search').type('Model-based testing');
}
}
});
// Run any cleanup after each test here
});
});
});
```
--------------------------------
### API Reference: testModel.getSimplePathPlans Method
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-test
Returns an array of testing plans based on the simple paths from the test model’s initial state to every other reachable state. Supports filtering.
```APIDOC
testModel.getSimplePathPlans(options?)
options?: object
filter: function(state) - Takes in the `state` and returns `true` if the state should be traversed, or `false` if traversal should stop.
```
--------------------------------
### useMachine (FSM) API Documentation
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-vue
Documents the `useMachine` Vue composition function specifically for `@xstate/fsm` machines. It outlines the `machine` argument and the returned object containing `state`, `send` function, and the `service` instance.
```APIDOC
useMachine(machine):
machine: An XState finite state machine (FSM) from @xstate/fsm.
Returns: {state, send, service}
state: Represents the current state of the machine as an @xstate/fsm StateMachine.State object.
send: A function that sends events to the running service.
service: The created @xstate/fsm service.
```
--------------------------------
### API Reference: model.withEvents Method
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-test
Provides testing details for each event. Each key in `eventsMap` is an object whose keys are event types and properties describe the execution and test cases for each event.
```APIDOC
model.withEvents(eventsMap)
eventsMap: object - An object whose keys are event types and properties describe the execution and test cases for each event.
exec: function(testContext: any, event: EventObject) - Function that executes the events.
cases?: EventObject[] - Sample event objects for this event type.
Example:
const toggleModel = createModel(toggleMachine).withEvents({
TOGGLE: {
exec: async (page) => {
await page.click('input');
},
},
});
```
--------------------------------
### Include XState Svelte FSM via CDN
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-svelte
This HTML snippet shows how to include the `@xstate/svelte/fsm` library via CDN, providing the `XStateSvelteFSM` global variable for use with finite state machines in Svelte.
```html
```
--------------------------------
### API Reference: useInterpret(machine, options?, observer?)
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-vue
Documentation for the `useInterpret` Vue composition function, which creates and returns a service from a given machine. It also allows for an optional observer to subscribe to the service's changes.
```APIDOC
useInterpret(machine, options?, observer?): Service
machine: The XState machine to interpret.
options (optional): Interpreter options for the service.
observer (optional): An observer object to subscribe to the service's state changes.
Returns: The created XState service.
```
--------------------------------
### Define XState Machine Configuration
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/basics/options
This snippet demonstrates the basic configuration of an XState machine, defining its states and entry actions. It shows the 'what' of the machine's behavior without including the implementation details.
```javascript
const helloMachine = createMachine({
/**
* Below is an 'action' — we’ll
* learn more about actions later
*/
entry: ['sayHello'],
});
```
--------------------------------
### API Reference: testModel.getShortestPathPlans Method
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-test
Returns an array of testing plans based on the shortest paths from the test model’s initial state to every other reachable state. Supports filtering.
```APIDOC
testModel.getShortestPathPlans(options?)
options?: object
filter: function(state) - Takes in the `state` and returns `true` if the state should be traversed, or `false` if traversal should stop.
Example:
const todosModel = createModel(todosMachine).withEvents({
/* ... */
});
const plans = todosModel.getShortestPathPlans({
// Tell the algorithm to limit state/event adjacency map to states
// that have less than 5 todos
filter: (state) => state.context.todos.length < 5,
});
```
--------------------------------
### Define states in an XState machine
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/basics/what-is-a-statechart
Illustrates how to define initial and named states within an XState machine using the `initial` and `states` properties. This example sets 'asleep' as the initial state and defines 'asleep' and 'awake' states.
```javascript
const machine = createMachine({
initial: 'asleep',
states: {
asleep: {},
awake: {},
},
});
```
--------------------------------
### Create and Transition XState FSM Machine
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-fsm
This example shows how to create a basic finite state machine using `createMachine` from `@xstate/fsm`. It defines a simple toggle machine with 'inactive' and 'active' states and demonstrates how to transition between states using the `transition` method.
```javascript
import { createMachine } from '@xstate/fsm';
const toggleMachine = createMachine({
id: 'toggle',
initial: 'inactive',
states: {
inactive: { on: { TOGGLE: 'active' } },
active: { on: { TOGGLE: 'inactive' } }
}
});
const { initialState } = toggleMachine;
const toggledState = toggleMachine.transition(initialState, 'TOGGLE');
toggledState.value;
const untoggledState = toggleMachine.transition(toggledState, 'TOGGLE');
untoggledState.value;
// => 'inactive'
```
--------------------------------
### Include XState Svelte via CDN (Standard)
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-svelte
This HTML snippet demonstrates how to include the `@xstate/svelte` library directly via CDN, making the `XStateSvelte` global variable available for use in your Svelte application.
```html
```
--------------------------------
### Import XState Vue via CDN (Full Build)
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-vue
This HTML script tag imports the full `xstate-vue.min.js` build via CDN, making the `XStateVue` global variable available for use in Vue applications.
```html
```
--------------------------------
### Define a simple pure function in TypeScript
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/model-based-testing/when-to-use
A basic TypeScript function that adds two numbers. This type of function typically requires no setup and is presented as an example of code not well-suited for model-based testing with `@xstate/test`.
```TypeScript
const add = (a: number, b: number) => {
return a + b;
};
```
--------------------------------
### XState TestPlan: Paths Property
Source: https://stately.ai/docs/xstate-v4/xstate/xstate/packages/xstate-test
An array property containing the testing paths required to get from the test model’s initial state to every other reachable state.
```APIDOC
testPlan.paths: TestPath[] - The testing paths to get from the test model’s initial state to every other reachable state.
```