-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
event.test.ts
134 lines (126 loc) · 3.31 KB
/
event.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import {
createMachine,
createActor,
assign,
AnyActorRef
} from '../src/index.ts';
import { sendTo } from '../src/actions/send';
describe('events', () => {
it('should be able to respond to sender by sending self', (done) => {
const authServerMachine = createMachine({
types: {
events: {} as { type: 'CODE'; sender: AnyActorRef }
},
id: 'authServer',
initial: 'waitingForCode',
states: {
waitingForCode: {
on: {
CODE: {
actions: sendTo(
({ event }) => {
expect(event.sender).toBeDefined();
return event.sender;
},
{ type: 'TOKEN' },
{ delay: 10 }
)
}
}
}
}
});
const authClientMachine = createMachine({
id: 'authClient',
initial: 'idle',
states: {
idle: {
on: { AUTH: 'authorizing' }
},
authorizing: {
invoke: {
id: 'auth-server',
src: authServerMachine
},
entry: sendTo('auth-server', ({ self }) => ({
type: 'CODE',
sender: self
})),
on: {
TOKEN: 'authorized'
}
},
authorized: {
type: 'final'
}
}
});
const service = createActor(authClientMachine);
service.subscribe({ complete: () => done() });
service.start();
service.send({ type: 'AUTH' });
});
});
describe('nested transitions', () => {
it('only take the transition of the most inner matching event', () => {
interface SignInContext {
email: string;
password: string;
}
interface ChangePassword {
type: 'changePassword';
password: string;
}
const authMachine = createMachine(
{
types: {} as { context: SignInContext; events: ChangePassword },
context: { email: '', password: '' },
initial: 'passwordField',
states: {
passwordField: {
initial: 'hidden',
states: {
hidden: {
on: {
// We want to assign the new password but remain in the hidden
// state
changePassword: {
actions: 'assignPassword'
}
}
},
valid: {},
invalid: {}
},
on: {
changePassword: [
{
guard: ({ event }) => event.password.length >= 10,
target: '.invalid',
actions: ['assignPassword']
},
{
target: '.valid',
actions: ['assignPassword']
}
]
}
}
}
},
{
actions: {
assignPassword: assign({
password: ({ event }) => event.password
})
}
}
);
const password = 'xstate123';
const actorRef = createActor(authMachine).start();
actorRef.send({ type: 'changePassword', password });
const snapshot = actorRef.getSnapshot();
expect(snapshot.value).toEqual({ passwordField: 'hidden' });
expect(snapshot.context).toEqual({ password, email: '' });
});
});