forked from slackapi/bolt-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp-basic-features.spec.ts
1327 lines (1202 loc) · 42.6 KB
/
App-basic-features.spec.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'mocha';
import sinon, { SinonSpy } from 'sinon';
import { assert } from 'chai';
import rewiremock from 'rewiremock';
import { LogLevel } from '@slack/logger';
import { WebClientOptions, WebClient } from '@slack/web-api';
import { Override, mergeOverrides, createFakeLogger } from './test-helpers';
import { ErrorCode } from './errors';
import {
Receiver,
ReceiverEvent,
SayFn,
NextFn,
} from './types';
import { ConversationStore } from './conversation-store';
import App from './App';
import SocketModeReceiver from './receivers/SocketModeReceiver';
// Utility functions
const noop = () => Promise.resolve(undefined);
const noopMiddleware = async ({ next }: { next: NextFn }) => {
await next();
};
const noopAuthorize = () => Promise.resolve({});
// Fakes
class FakeReceiver implements Receiver {
private bolt: App | undefined;
public init = (bolt: App) => {
this.bolt = bolt;
};
public start = sinon.fake((...params: any[]): Promise<unknown> => Promise.resolve([...params]));
public stop = sinon.fake((...params: any[]): Promise<unknown> => Promise.resolve([...params]));
public async sendEvent(event: ReceiverEvent): Promise<void> {
return this.bolt?.processEvent(event);
}
}
// Dummies (values that have no real behavior but pass through the system opaquely)
function createDummyReceiverEvent(type: string = 'dummy_event_type'): ReceiverEvent {
// NOTE: this is a degenerate ReceiverEvent that would successfully pass through the App. it happens to look like a
// IncomingEventType.Event
return {
body: {
event: {
type,
},
},
ack: noop,
};
}
describe('App basic features', () => {
describe('constructor', () => {
describe('with a custom port value in HTTP Mode', () => {
const fakeBotId = 'B_FAKE_BOT_ID';
const fakeBotUserId = 'U_FAKE_BOT_USER_ID';
const overrides = mergeOverrides(
withNoopAppMetadata(),
withSuccessfulBotUserFetchingWebClient(fakeBotId, fakeBotUserId),
);
it('should accept a port value at the top-level', async () => {
// Arrange
const MockApp = await importApp(overrides);
// Act
const app = new MockApp({ token: '', signingSecret: '', port: 9999 });
// Assert
assert.equal((app as any).receiver.port, 9999);
});
it('should accept a port value under installerOptions', async () => {
// Arrange
const MockApp = await importApp(overrides);
// Act
const app = new MockApp({ token: '', signingSecret: '', port: 7777, installerOptions: { port: 9999 } });
// Assert
assert.equal((app as any).receiver.port, 9999);
});
});
describe('with a custom port value in Socket Mode', () => {
const fakeBotId = 'B_FAKE_BOT_ID';
const fakeBotUserId = 'U_FAKE_BOT_USER_ID';
const installationStore = {
storeInstallation: async () => { },
fetchInstallation: async () => { throw new Error('Failed fetching installation'); },
deleteInstallation: async () => { },
};
const overrides = mergeOverrides(
withNoopAppMetadata(),
withSuccessfulBotUserFetchingWebClient(fakeBotId, fakeBotUserId),
);
it('should accept a port value at the top-level', async () => {
// Arrange
const MockApp = await importApp(overrides);
// Act
const app = new MockApp({
socketMode: true,
appToken: '',
port: 9999,
clientId: '',
clientSecret: '',
stateSecret: '',
installerOptions: {
},
installationStore,
});
// Assert
assert.equal((app as any).receiver.httpServerPort, 9999);
});
it('should accept a port value under installerOptions', async () => {
// Arrange
const MockApp = await importApp(overrides);
// Act
const app = new MockApp({
socketMode: true,
appToken: '',
port: 7777,
clientId: '',
clientSecret: '',
stateSecret: '',
installerOptions: {
port: 9999,
},
installationStore,
});
// Assert
assert.equal((app as any).receiver.httpServerPort, 9999);
});
});
// TODO: test when the single team authorization results fail. that should still succeed but warn. it also means
// that the `ignoreSelf` middleware will fail (or maybe just warn) a bunch.
describe('with successful single team authorization results', () => {
it('should succeed with a token for single team authorization', async () => {
// Arrange
const fakeBotId = 'B_FAKE_BOT_ID';
const fakeBotUserId = 'U_FAKE_BOT_USER_ID';
const overrides = mergeOverrides(
withNoopAppMetadata(),
withSuccessfulBotUserFetchingWebClient(fakeBotId, fakeBotUserId),
);
const MockApp = await importApp(overrides);
// Act
const app = new MockApp({ token: '', signingSecret: '' });
// Assert
// TODO: verify that the fake bot ID and fake bot user ID are retrieved
assert.instanceOf(app, MockApp);
});
it('should pass the given token to app.client', async () => {
// Arrange
const fakeBotId = 'B_FAKE_BOT_ID';
const fakeBotUserId = 'U_FAKE_BOT_USER_ID';
const overrides = mergeOverrides(
withNoopAppMetadata(),
withSuccessfulBotUserFetchingWebClient(fakeBotId, fakeBotUserId),
);
const MockApp = await importApp(overrides);
// Act
const app = new MockApp({ token: 'xoxb-foo-bar', signingSecret: '' });
// Assert
assert.isDefined(app.client);
assert.equal(app.client.token, 'xoxb-foo-bar');
});
});
it('should succeed with an authorize callback', async () => {
// Arrange
const authorizeCallback = sinon.fake();
const MockApp = await importApp();
// Act
const app = new MockApp({ authorize: authorizeCallback, signingSecret: '' });
// Assert
assert(authorizeCallback.notCalled, 'Should not call the authorize callback on instantiation');
assert.instanceOf(app, MockApp);
});
it('should fail without a token for single team authorization, authorize callback, nor oauth installer', async () => {
// Arrange
const MockApp = await importApp();
// Act
try {
new MockApp({ signingSecret: '' }); // eslint-disable-line no-new
assert.fail();
} catch (error: any) {
// Assert
assert.propertyVal(error, 'code', ErrorCode.AppInitializationError);
}
});
it('should fail when both a token and authorize callback are specified', async () => {
// Arrange
const authorizeCallback = sinon.fake();
const MockApp = await importApp();
// Act
try {
new MockApp({ token: '', authorize: authorizeCallback, signingSecret: '' }); // eslint-disable-line no-new
assert.fail();
} catch (error: any) {
// Assert
assert.propertyVal(error, 'code', ErrorCode.AppInitializationError);
assert(authorizeCallback.notCalled);
}
});
it('should fail when both a token is specified and OAuthInstaller is initialized', async () => {
// Arrange
const authorizeCallback = sinon.fake();
const MockApp = await importApp();
// Act
try {
new MockApp({ token: '', clientId: '', clientSecret: '', stateSecret: '', signingSecret: '' }); // eslint-disable-line no-new
assert.fail();
} catch (error: any) {
// Assert
assert.propertyVal(error, 'code', ErrorCode.AppInitializationError);
assert(authorizeCallback.notCalled);
}
});
it('should fail when both a authorize callback is specified and OAuthInstaller is initialized', async () => {
// Arrange
const authorizeCallback = sinon.fake();
const MockApp = await importApp();
// Act
try {
new MockApp({ authorize: authorizeCallback, clientId: '', clientSecret: '', stateSecret: '', signingSecret: '' }); // eslint-disable-line no-new
assert.fail();
} catch (error: any) {
// Assert
assert.propertyVal(error, 'code', ErrorCode.AppInitializationError);
assert(authorizeCallback.notCalled);
}
});
describe('with a custom receiver', () => {
it('should succeed with no signing secret', async () => {
// Arrange
const MockApp = await importApp();
// Act
const app = new MockApp({ receiver: new FakeReceiver(), authorize: noopAuthorize });
// Assert
assert.instanceOf(app, MockApp);
});
});
it('should fail when no signing secret for the default receiver is specified', async () => {
// Arrange
const MockApp = await importApp();
// Act
try {
new MockApp({ authorize: noopAuthorize }); // eslint-disable-line no-new
assert.fail();
} catch (error: any) {
// Assert
assert.propertyVal(error, 'code', ErrorCode.AppInitializationError);
}
});
it('should fail when both socketMode and a custom receiver are specified', async () => {
// Arrange
const fakeReceiver = new FakeReceiver();
const MockApp = await importApp();
// Act
try {
new MockApp({ token: '', signingSecret: '', socketMode: true, receiver: fakeReceiver }); // eslint-disable-line no-new
assert.fail();
} catch (error: any) {
// Assert
assert.propertyVal(error, 'code', ErrorCode.AppInitializationError);
}
});
it('should succeed when both socketMode and SocketModeReceiver are specified', async () => {
// Arrange
const fakeBotId = 'B_FAKE_BOT_ID';
const fakeBotUserId = 'U_FAKE_BOT_USER_ID';
const overrides = mergeOverrides(
withNoopAppMetadata(),
withSuccessfulBotUserFetchingWebClient(fakeBotId, fakeBotUserId),
);
const MockApp = await importApp(overrides);
const socketModeReceiver = new SocketModeReceiver({ appToken: '' });
// Act
const app = new MockApp({ token: '', signingSecret: '', socketMode: true, receiver: socketModeReceiver });
// Assert
assert.instanceOf(app, MockApp);
});
it('should initialize MemoryStore conversation store by default', async () => {
// Arrange
const fakeMemoryStore = sinon.fake();
const fakeConversationContext = sinon.fake.returns(noopMiddleware);
const overrides = mergeOverrides(
withNoopAppMetadata(),
withNoopWebClient(),
withMemoryStore(fakeMemoryStore),
withConversationContext(fakeConversationContext),
);
const MockApp = await importApp(overrides);
// Act
const app = new MockApp({ authorize: noopAuthorize, signingSecret: '' });
// Assert
assert.instanceOf(app, MockApp);
assert(fakeMemoryStore.calledWithNew);
assert(fakeConversationContext.called);
});
it('should initialize without a conversation store when option is false', async () => {
// Arrange
const fakeConversationContext = sinon.fake.returns(noopMiddleware);
const overrides = mergeOverrides(
withNoopAppMetadata(),
withNoopWebClient(),
withConversationContext(fakeConversationContext),
);
const MockApp = await importApp(overrides);
// Act
const app = new MockApp({ convoStore: false, authorize: noopAuthorize, signingSecret: '' });
// Assert
assert.instanceOf(app, MockApp);
assert(fakeConversationContext.notCalled);
});
describe('with a custom conversation store', () => {
it('should initialize the conversation store', async () => {
// Arrange
const fakeConversationContext = sinon.fake.returns(noopMiddleware);
const overrides = mergeOverrides(
withNoopAppMetadata(),
withNoopWebClient(),
withConversationContext(fakeConversationContext),
);
const dummyConvoStore = Symbol() as unknown as ConversationStore;
const MockApp = await importApp(overrides);
// Act
const app = new MockApp({ convoStore: dummyConvoStore, authorize: noopAuthorize, signingSecret: '' });
// Assert
assert.instanceOf(app, MockApp);
assert(fakeConversationContext.firstCall.calledWith(dummyConvoStore));
});
});
describe('with custom redirectUri supplied', () => {
it('should fail when missing installerOptions', async () => {
// Arrange
const MockApp = await importApp();
// Act
try {
new MockApp({ token: '', signingSecret: '', redirectUri: 'http://example.com/redirect' }); // eslint-disable-line no-new
assert.fail();
} catch (error: any) {
// Assert
assert.propertyVal(error, 'code', ErrorCode.AppInitializationError);
}
});
it('should fail when missing installerOptions.redirectUriPath', async () => {
// Arrange
const MockApp = await importApp();
// Act
try {
new MockApp({ token: '', signingSecret: '', redirectUri: 'http://example.com/redirect', installerOptions: {} }); // eslint-disable-line no-new
assert.fail();
} catch (error: any) {
// Assert
assert.propertyVal(error, 'code', ErrorCode.AppInitializationError);
}
});
});
it('with clientOptions', async () => {
const fakeConstructor = sinon.fake();
const overrides = mergeOverrides(withNoopAppMetadata(), {
'@slack/web-api': {
WebClient: class {
public constructor() {
fakeConstructor(...arguments); // eslint-disable-line prefer-rest-params
}
},
},
});
const MockApp = await importApp(overrides);
const clientOptions = { slackApiUrl: 'proxy.slack.com' };
new MockApp({ clientOptions, authorize: noopAuthorize, signingSecret: '', logLevel: LogLevel.ERROR }); // eslint-disable-line no-new
assert.ok(fakeConstructor.called);
const [token, options] = fakeConstructor.lastCall.args;
assert.strictEqual(undefined, token, 'token should be undefined');
assert.strictEqual(clientOptions.slackApiUrl, options.slackApiUrl);
assert.strictEqual(LogLevel.ERROR, options.logLevel, 'override logLevel');
});
it('should not perform auth.test API call if tokenVerificationEnabled is false', async () => {
// Arrange
const fakeConstructor = sinon.fake();
const overrides = mergeOverrides(withNoopAppMetadata(), {
'@slack/web-api': {
WebClient: class {
public constructor() {
fakeConstructor(...arguments); // eslint-disable-line prefer-rest-params
}
public auth = {
test: () => {
throw new Error('This API method call should not be performed');
},
};
},
},
});
const MockApp = await importApp(overrides);
const app = new MockApp({
token: 'xoxb-completely-invalid-token',
signingSecret: 'invalid-one',
tokenVerificationEnabled: false,
});
// Assert
assert.instanceOf(app, MockApp);
});
it('should fail in await App#init()', async () => {
// Arrange
const fakeConstructor = sinon.fake();
const overrides = mergeOverrides(withNoopAppMetadata(), {
'@slack/web-api': {
WebClient: class {
public constructor() {
fakeConstructor(...arguments); // eslint-disable-line prefer-rest-params
}
public auth = {
test: () => {
throw new Error('Failing for init() test!');
},
};
},
},
});
const MockApp = await importApp(overrides);
const app = new MockApp({
token: 'xoxb-completely-invalid-token',
signingSecret: 'invalid-one',
deferInitialization: true,
});
// Assert
assert.instanceOf(app, MockApp);
try {
// call #start() before #init()
await app.start();
assert.fail('The start() method should fail before init() call');
} catch (err: any) {
assert.equal(err.message, 'This App instance is not yet initialized. Call `await App#init()` before starting the app.');
}
try {
await app.init();
assert.fail('The init() method should fail here');
} catch (err: any) {
assert.equal(err.message, 'Failing for init() test!');
}
});
describe('with developerMode', () => {
it('should accept developerMode: true', async () => {
// Arrange
const overrides = mergeOverrides(
withNoopAppMetadata(),
withSuccessfulBotUserFetchingWebClient('B_FAKE_BOT_ID', 'U_FAKE_BOT_USER_ID'),
);
const fakeLogger = createFakeLogger();
const MockApp = await importApp(overrides);
// Act
const app = new MockApp({ logger: fakeLogger, token: '', appToken: '', developerMode: true });
// Assert
assert.equal((app as any).logLevel, LogLevel.DEBUG);
assert.equal((app as any).socketMode, true);
});
});
// TODO: tests for ignoreSelf option
// TODO: tests for logger and logLevel option
// TODO: tests for providing botId and botUserId options
// TODO: tests for providing endpoints option
});
describe('#start', () => {
// The following test case depends on a definition of App that is generic on its Receiver type. This will be
// addressed in the future. It cannot even be left uncommented with the `it.skip()` global because it will fail
// TypeScript compilation as written.
// it('should pass calls through to receiver', async () => {
// // Arrange
// const dummyReturn = Symbol();
// const dummyParams = [Symbol(), Symbol()];
// const fakeReceiver = new FakeReceiver();
// const MockApp = await importApp();
// const app = new MockApp({ receiver: fakeReceiver, authorize: noopAuthorize });
// fakeReceiver.start = sinon.fake.returns(dummyReturn);
// // Act
// const actualReturn = await app.start(...dummyParams);
// // Assert
// assert.deepEqual(actualReturn, dummyReturn);
// assert.deepEqual(dummyParams, fakeReceiver.start.firstCall.args);
// });
// TODO: another test case to take the place of the one above (for coverage until the definition of App is made
// generic).
});
describe('#stop', () => {
it('should pass calls through to receiver', async () => {
// Arrange
const dummyReturn = Symbol();
const dummyParams = [Symbol(), Symbol()];
const fakeReceiver = new FakeReceiver();
const MockApp = await importApp();
fakeReceiver.stop = sinon.fake.returns(dummyReturn);
// Act
const app = new MockApp({ receiver: fakeReceiver, authorize: noopAuthorize });
const actualReturn = await app.stop(...dummyParams);
// Assert
assert.deepEqual(actualReturn, dummyReturn);
assert.deepEqual(dummyParams, fakeReceiver.stop.firstCall.args);
});
});
let fakeReceiver: FakeReceiver;
let fakeErrorHandler: SinonSpy;
let dummyAuthorizationResult: { botToken: string; botId: string };
beforeEach(() => {
fakeReceiver = new FakeReceiver();
fakeErrorHandler = sinon.fake();
dummyAuthorizationResult = { botToken: '', botId: '' };
});
describe('middleware and listener arguments', () => {
const dummyChannelId = 'CHANNEL_ID';
let overrides: Override;
const baseEvent = createDummyReceiverEvent();
function buildOverrides(secondOverrides: Override[]): Override {
overrides = mergeOverrides(
withNoopAppMetadata(),
...secondOverrides,
withMemoryStore(sinon.fake()),
withConversationContext(sinon.fake.returns(noopMiddleware)),
);
return overrides;
}
describe('respond()', () => {
it('should respond to events with a response_url', async () => {
// Arrange
const responseText = 'response';
const responseUrl = 'https://fake.slack/response_url';
const actionId = 'block_action_id';
const fakeAxiosPost = sinon.fake.resolves({});
overrides = buildOverrides([withNoopWebClient(), withAxiosPost(fakeAxiosPost)]);
const MockApp = await importApp(overrides);
// Act
const app = new MockApp({ receiver: fakeReceiver, authorize: sinon.fake.resolves(dummyAuthorizationResult) });
app.action(actionId, async ({ respond }) => {
await respond(responseText);
});
app.error(fakeErrorHandler);
await fakeReceiver.sendEvent({
// IncomingEventType.Action (app.action)
body: {
type: 'block_actions',
response_url: responseUrl,
actions: [
{
action_id: actionId,
},
],
channel: {},
user: {},
team: {},
},
ack: noop,
});
// Assert
assert(fakeErrorHandler.notCalled);
assert.equal(fakeAxiosPost.callCount, 1);
// Assert that each call to fakeAxiosPost had the right arguments
assert(fakeAxiosPost.calledWith(responseUrl, { text: responseText }));
});
it('should respond with a response object', async () => {
// Arrange
const responseObject = { text: 'response' };
const responseUrl = 'https://fake.slack/response_url';
const actionId = 'block_action_id';
const fakeAxiosPost = sinon.fake.resolves({});
overrides = buildOverrides([withNoopWebClient(), withAxiosPost(fakeAxiosPost)]);
const MockApp = await importApp(overrides);
// Act
const app = new MockApp({ receiver: fakeReceiver, authorize: sinon.fake.resolves(dummyAuthorizationResult) });
app.action(actionId, async ({ respond }) => {
await respond(responseObject);
});
app.error(fakeErrorHandler);
await fakeReceiver.sendEvent({
// IncomingEventType.Action (app.action)
body: {
type: 'block_actions',
response_url: responseUrl,
actions: [
{
action_id: actionId,
},
],
channel: {},
user: {},
team: {},
},
ack: noop,
});
// Assert
assert.equal(fakeAxiosPost.callCount, 1);
// Assert that each call to fakeAxiosPost had the right arguments
assert(fakeAxiosPost.calledWith(responseUrl, responseObject));
});
it('should be able to use respond for view_submission payloads', async () => {
// Arrange
const responseObject = { text: 'response' };
const responseUrl = 'https://fake.slack/response_url';
const fakeAxiosPost = sinon.fake.resolves({});
overrides = buildOverrides([withNoopWebClient(), withAxiosPost(fakeAxiosPost)]);
const MockApp = await importApp(overrides);
// Act
const app = new MockApp({ receiver: fakeReceiver, authorize: sinon.fake.resolves(dummyAuthorizationResult) });
app.view('view-id', async ({ respond }) => {
await respond(responseObject);
});
app.error(fakeErrorHandler);
await fakeReceiver.sendEvent({
ack: noop,
body: {
type: 'view_submission',
team: {},
user: {},
view: {
id: 'V111',
type: 'modal',
callback_id: 'view-id',
state: {},
title: {},
close: {},
submit: {},
},
response_urls: [
{
block_id: 'b',
action_id: 'a',
channel_id: 'C111',
response_url: 'https://fake.slack/response_url',
},
],
},
});
// Assert
assert.equal(fakeAxiosPost.callCount, 1);
// Assert that each call to fakeAxiosPost had the right arguments
assert(fakeAxiosPost.calledWith(responseUrl, responseObject));
});
});
describe('logger', () => {
it('should be available in middleware/listener args', async () => {
// Arrange
const MockApp = await importApp(overrides);
const fakeLogger = createFakeLogger();
const app = new MockApp({
logger: fakeLogger,
receiver: fakeReceiver,
authorize: sinon.fake.resolves(dummyAuthorizationResult),
});
app.use(async ({ logger, body, next }) => {
logger.info(body);
await next();
});
app.event('app_home_opened', async ({ logger, event }) => {
logger.debug(event);
});
const receiverEvents = [
{
body: {
type: 'event_callback',
token: 'XXYYZZ',
team_id: 'TXXXXXXXX',
api_app_id: 'AXXXXXXXXX',
event: {
type: 'app_home_opened',
event_ts: '1234567890.123456',
user: 'UXXXXXXX1',
text: 'hello friends!',
tab: 'home',
view: {},
},
},
respond: noop,
ack: noop,
},
];
// Act
await Promise.all(receiverEvents.map((event) => fakeReceiver.sendEvent(event)));
// Assert
assert.isTrue(fakeLogger.info.called);
assert.isTrue(fakeLogger.debug.called);
});
it('should work in the case both logger and logLevel are given', async () => {
// Arrange
const MockApp = await importApp(overrides);
const fakeLogger = createFakeLogger();
const app = new MockApp({
logger: fakeLogger,
logLevel: LogLevel.DEBUG,
receiver: fakeReceiver,
authorize: sinon.fake.resolves(dummyAuthorizationResult),
});
app.use(async ({ logger, body, next }) => {
logger.info(body);
await next();
});
app.event('app_home_opened', async ({ logger, event }) => {
logger.debug(event);
});
const receiverEvents = [
{
body: {
type: 'event_callback',
token: 'XXYYZZ',
team_id: 'TXXXXXXXX',
api_app_id: 'AXXXXXXXXX',
event: {
type: 'app_home_opened',
event_ts: '1234567890.123456',
user: 'UXXXXXXX1',
text: 'hello friends!',
tab: 'home',
view: {},
},
},
respond: noop,
ack: noop,
},
];
// Act
await Promise.all(receiverEvents.map((event) => fakeReceiver.sendEvent(event)));
// Assert
assert.isTrue(fakeLogger.info.called);
assert.isTrue(fakeLogger.debug.called);
assert.isTrue(fakeLogger.setLevel.called);
});
});
describe('client', () => {
it('should be available in middleware/listener args', async () => {
// Arrange
const MockApp = await importApp(
mergeOverrides(
withNoopAppMetadata(),
withSuccessfulBotUserFetchingWebClient('B123', 'U123'),
),
);
const tokens = ['xoxb-123', 'xoxp-456', 'xoxb-123'];
const app = new MockApp({
receiver: fakeReceiver,
authorize: () => {
const token = tokens.pop();
if (typeof token === 'undefined') {
return Promise.resolve({ botId: 'B123' });
}
if (token.startsWith('xoxb-')) {
return Promise.resolve({ botToken: token, botId: 'B123' });
}
return Promise.resolve({ userToken: token, botId: 'B123' });
},
});
app.use(async ({ client, next }) => {
await client.auth.test();
await next();
});
const clients: WebClient[] = [];
app.event('app_home_opened', async ({ client }) => {
clients.push(client);
await client.auth.test();
});
const event = {
body: {
type: 'event_callback',
token: 'legacy',
team_id: 'T123',
api_app_id: 'A123',
event: {
type: 'app_home_opened',
event_ts: '123.123',
user: 'U123',
text: 'Hi there!',
tab: 'home',
view: {},
},
},
respond: noop,
ack: noop,
};
const receiverEvents = [event, event, event];
// Act
await Promise.all(receiverEvents.map((evt) => fakeReceiver.sendEvent(evt)));
// Assert
assert.isUndefined(app.client.token);
assert.equal(clients[0].token, 'xoxb-123');
assert.equal(clients[1].token, 'xoxp-456');
assert.equal(clients[2].token, 'xoxb-123');
assert.notEqual(clients[0], clients[1]);
assert.strictEqual(clients[0], clients[2]);
});
it("should be to the global app client when authorization doesn't produce a token", async () => {
// Arrange
const MockApp = await importApp();
const app = new MockApp({
receiver: fakeReceiver,
authorize: noopAuthorize,
ignoreSelf: false,
});
const globalClient = app.client;
// Act
let clientArg: WebClient | undefined;
app.use(async ({ client }) => {
clientArg = client;
});
await fakeReceiver.sendEvent(createDummyReceiverEvent());
// Assert
assert.equal(globalClient, clientArg);
});
});
describe('say()', () => {
function createChannelContextualReceiverEvents(channelId: string): ReceiverEvent[] {
return [
// IncomingEventType.Event with channel in payload
{
...baseEvent,
body: {
event: {
channel: channelId,
},
team_id: 'TEAM_ID',
},
},
// IncomingEventType.Event with channel in item
{
...baseEvent,
body: {
event: {
item: {
channel: channelId,
},
},
team_id: 'TEAM_ID',
},
},
// IncomingEventType.Command
{
...baseEvent,
body: {
command: '/COMMAND_NAME',
channel_id: channelId,
team_id: 'TEAM_ID',
},
},
// IncomingEventType.Action from block action, interactive message, or message action
{
...baseEvent,
body: {
actions: [{}],
channel: {
id: channelId,
},
user: {
id: 'USER_ID',
},
team: {
id: 'TEAM_ID',
},
},
},
// IncomingEventType.Action from dialog submission
{
...baseEvent,
body: {
type: 'dialog_submission',
channel: {
id: channelId,
},
user: {
id: 'USER_ID',
},
team: {
id: 'TEAM_ID',
},
},
},
];
}
it('should send a simple message to a channel where the incoming event originates', async () => {
// Arrange
const fakePostMessage = sinon.fake.resolves({});
overrides = buildOverrides([withPostMessage(fakePostMessage)]);
const MockApp = await importApp(overrides);
const dummyMessage = 'test';
const dummyReceiverEvents = createChannelContextualReceiverEvents(dummyChannelId);
// Act
const app = new MockApp({ receiver: fakeReceiver, authorize: sinon.fake.resolves(dummyAuthorizationResult) });
app.use(async (args) => {
// By definition, these events should all produce a say function, so we cast args.say into a SayFn
const say = (args as any).say as SayFn;
await say(dummyMessage);
});
app.error(fakeErrorHandler);
await Promise.all(dummyReceiverEvents.map((event) => fakeReceiver.sendEvent(event)));
// Assert
assert.equal(fakePostMessage.callCount, dummyReceiverEvents.length);
// Assert that each call to fakePostMessage had the right arguments
fakePostMessage.getCalls().forEach((call) => {
const firstArg = call.args[0];
assert.propertyVal(firstArg, 'text', dummyMessage);
assert.propertyVal(firstArg, 'channel', dummyChannelId);
});
assert(fakeErrorHandler.notCalled);
});
it('should send a complex message to a channel where the incoming event originates', async () => {
// Arrange
const fakePostMessage = sinon.fake.resolves({});
overrides = buildOverrides([withPostMessage(fakePostMessage)]);
const MockApp = await importApp(overrides);
const dummyMessage = { text: 'test' };
const dummyReceiverEvents = createChannelContextualReceiverEvents(dummyChannelId);
// Act
const app = new MockApp({ receiver: fakeReceiver, authorize: sinon.fake.resolves(dummyAuthorizationResult) });
app.use(async (args) => {
// By definition, these events should all produce a say function, so we cast args.say into a SayFn
const say = (args as any).say as SayFn;
await say(dummyMessage);
});
app.error(fakeErrorHandler);
await Promise.all(dummyReceiverEvents.map((event) => fakeReceiver.sendEvent(event)));
// Assert
assert.equal(fakePostMessage.callCount, dummyReceiverEvents.length);
// Assert that each call to fakePostMessage had the right arguments