Skip to content

Instantly share code, notes, and snippets.

@with-heart
Last active August 17, 2024 19:03
Show Gist options
  • Save with-heart/c6bf7921672cb0a1f03cc52cf0afeac4 to your computer and use it in GitHub Desktop.
Save with-heart/c6bf7921672cb0a1f03cc52cf0afeac4 to your computer and use it in GitHub Desktop.
`vitest`->`jest` conversion: before/after examples of `done` callback to alternative callback styles
import { createActor, createMachine, waitFor } from '../src';
// 1
test('async test 1', async () => {
const { promise, resolve } = Promise.withResolvers<void>();
const machine = createMachine({
entry: () => resolve()
});
createActor(machine).start();
await promise;
});
// 2
test('async test 2', async () => {
const machine = createMachine({
initial: 'idle',
states: {
idle: {
on: {
START: 'running'
}
},
running: {
after: {
100: 'complete'
}
},
complete: {
type: 'final'
}
}
});
const actor = createActor(machine).start();
actor.send({ type: 'START' });
// wait for the actor to be 'done' (in a `final` state)
await waitFor(actor, (snapshot) => snapshot.status === 'done');
expect(actor.getSnapshot().value).toBe('complete');
});
import { createActor, createMachine } from '../src';
// 1
test('async test 1', (done) => {
const machine = createMachine({
entry: () => done()
});
createActor(machine).start();
});
// 2
test('async test 2', (done) => {
const machine = createMachine({
initial: 'idle',
states: {
idle: {
on: {
START: 'running'
}
},
running: {
after: {
100: 'complete'
}
},
complete: {
type: 'final'
}
}
});
const actor = createActor(machine).start();
actor.send({ type: 'START' });
setTimeout(() => {
expect(actor.getSnapshot().value).toBe('complete');
done();
}, 100);
});
--- packages/core/src/before.test.ts 2024-08-17 15:02:10
+++ packages/core/src/after.test.ts 2024-08-17 15:02:18
@@ -1,15 +1,19 @@
-import { createActor, createMachine } from '../src';
+import { createActor, createMachine, waitFor } from '../src';
// 1
-test('async test 1', (done) => {
+test('async test 1', async () => {
+ const { promise, resolve } = Promise.withResolvers<void>();
+
const machine = createMachine({
- entry: () => done()
+ entry: () => resolve()
});
createActor(machine).start();
+
+ await promise;
});
// 2
-test('async test 2', (done) => {
+test('async test 2', async () => {
const machine = createMachine({
initial: 'idle',
states: {
@@ -31,8 +35,8 @@
const actor = createActor(machine).start();
actor.send({ type: 'START' });
- setTimeout(() => {
- expect(actor.getSnapshot().value).toBe('complete');
- done();
- }, 100);
+ // wait for the actor to be 'done' (in a `final` state)
+ await waitFor(actor, (snapshot) => snapshot.status === 'done');
+
+ expect(actor.getSnapshot().value).toBe('complete');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment