forked from tilt-dev/tilt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApiButton.test.tsx
592 lines (521 loc) · 18.1 KB
/
ApiButton.test.tsx
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
import {
render,
RenderOptions,
RenderResult,
screen,
waitFor,
} from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import fetchMock from "fetch-mock"
import { SnackbarProvider } from "notistack"
import React, { PropsWithChildren } from "react"
import { MemoryRouter } from "react-router"
import { AnalyticsAction } from "./analytics"
import {
cleanupMockAnalyticsCalls,
expectIncrs,
mockAnalyticsCalls,
nonAnalyticsCalls,
} from "./analytics_test_helpers"
import {
ApiButton,
ApiButtonType,
buttonsByComponent,
ButtonSet,
} from "./ApiButton"
import { mockUIButtonUpdates } from "./ApiButton.testhelpers"
import { accessorsForTesting, tiltfileKeyContext } from "./BrowserStorage"
import { HudErrorContextProvider } from "./HudErrorContext"
import {
boolFieldForUIButton,
choiceFieldForUIButton,
disableButton,
hiddenFieldForUIButton,
oneUIButton,
textFieldForUIButton,
} from "./testdata"
import { UIButton, UIButtonStatus, UIInputSpec } from "./types"
const buttonInputsAccessor = accessorsForTesting(
`apibutton-TestButton`,
localStorage
)
type ApiButtonProviderProps = {
setError?: (error: string) => void
}
function ApiButtonProviders({
children,
setError,
}: PropsWithChildren<ApiButtonProviderProps>) {
return (
<MemoryRouter>
<HudErrorContextProvider setError={setError ?? (() => {})}>
<tiltfileKeyContext.Provider value="test">
<SnackbarProvider>{children}</SnackbarProvider>
</tiltfileKeyContext.Provider>
</HudErrorContextProvider>
</MemoryRouter>
)
}
// Following the custom render example from RTL:
// https://testing-library.com/docs/react-testing-library/setup/#custom-render
function customRender(
component: JSX.Element,
options?: RenderOptions,
providerProps?: ApiButtonProviderProps
) {
return render(component, {
wrapper: ({ children }) => (
<ApiButtonProviders {...providerProps} children={children} />
),
...options,
})
}
describe("ApiButton", () => {
beforeEach(() => {
localStorage.clear()
fetchMock.reset()
mockAnalyticsCalls()
mockUIButtonUpdates()
Date.now = jest.fn(() => 1482363367071)
})
afterEach(() => {
localStorage.clear()
cleanupMockAnalyticsCalls()
})
it("renders a simple button", () => {
const uibutton = oneUIButton({ iconName: "flight_takeoff" })
customRender(<ApiButton uiButton={uibutton} />)
const buttonElement = screen.getByLabelText(
`Trigger ${uibutton.spec!.text!}`
)
expect(buttonElement).toBeInTheDocument()
expect(buttonElement).toHaveTextContent(uibutton.spec!.text!)
expect(screen.getByText(uibutton.spec!.iconName!)).toBeInTheDocument()
})
it("sends analytics when clicked", async () => {
const uibutton = oneUIButton({})
customRender(<ApiButton uiButton={uibutton} />)
userEvent.click(screen.getByRole("button"))
await waitFor(() => {
expectIncrs({
name: "ui.web.uibutton",
tags: {
action: AnalyticsAction.Click,
component: ApiButtonType.Global,
},
})
})
})
it("sets a hud error when the api request fails", async () => {
// To add a mocked error response, reset the current mock
// for UIButton API call and add back the mock for analytics calls
// Reset the current mock for UIButton to add fake error response
fetchMock.reset()
mockAnalyticsCalls()
fetchMock.put(
(url) => url.startsWith("/proxy/apis/tilt.dev/v1alpha1/uibuttons"),
{ throws: "broken!" }
)
let error: string | undefined
const setError = (e: string) => (error = e)
const uibutton = oneUIButton({})
customRender(<ApiButton uiButton={uibutton} />, {}, { setError })
userEvent.click(screen.getByRole("button"))
await waitFor(() => {
expect(screen.getByRole("button")).not.toBeDisabled()
})
expect(error).toEqual("Error submitting button click: broken!")
})
describe("button with visible inputs", () => {
let uibutton: UIButton
let inputSpecs: UIInputSpec[]
beforeEach(() => {
inputSpecs = [
textFieldForUIButton("text_field"),
boolFieldForUIButton("bool_field", false),
textFieldForUIButton("text_field_with_default", "default text"),
hiddenFieldForUIButton("hidden_field", "hidden value 1"),
choiceFieldForUIButton("choice_field", [
"choice1",
"choice2",
"choice3",
]),
]
uibutton = oneUIButton({ inputSpecs })
customRender(<ApiButton uiButton={uibutton} />).rerender
})
it("renders an options button", () => {
expect(
screen.getByLabelText(`Open ${uibutton.spec!.text!} options`)
).toBeInTheDocument()
})
it("shows the options form with inputs when the options button is clicked", () => {
const optionButton = screen.getByLabelText(
`Open ${uibutton.spec!.text!} options`
)
userEvent.click(optionButton)
expect(
screen.getByText(`Options for ${uibutton.spec!.text!}`)
).toBeInTheDocument()
})
it("only shows inputs for visible inputs", () => {
// Open the options dialog first
const optionButton = screen.getByLabelText(
`Open ${uibutton.spec!.text!} options`
)
userEvent.click(optionButton)
inputSpecs.forEach((spec) => {
if (!spec.hidden) {
expect(screen.getByLabelText(spec.label!)).toBeInTheDocument()
}
})
})
it("allows an empty text string when there's a default value", async () => {
// Open the options dialog first
const optionButton = screen.getByLabelText(
`Open ${uibutton.spec!.text!} options`
)
userEvent.click(optionButton)
// Get the input element with the hardcoded default text
const inputWithDefault = screen.getByDisplayValue("default text")
userEvent.clear(inputWithDefault)
// Use the label text to select and verify the input's value
expect(screen.getByLabelText("text_field_with_default")).toHaveValue("")
})
it("propagates analytics tags to text inputs", async () => {
// Open the options dialog first
const optionButton = screen.getByLabelText(
`Open ${uibutton.spec!.text!} options`
)
userEvent.click(optionButton)
const booleanInput = screen.getByLabelText("bool_field")
userEvent.click(booleanInput)
expect(screen.getByLabelText("bool_field")).toBeChecked()
await waitFor(() => {
expectIncrs(
{
name: "ui.web.uibutton.inputMenu",
tags: {
action: AnalyticsAction.Click,
component: ApiButtonType.Global,
},
},
{
name: "ui.web.uibutton.inputValue",
tags: {
action: AnalyticsAction.Edit,
component: ApiButtonType.Global,
inputType: "bool",
},
}
)
})
})
it("submits the current options when the submit button is clicked", async () => {
// Open the options dialog first
const optionButton = screen.getByLabelText(
`Open ${uibutton.spec!.text!} options`
)
userEvent.click(optionButton)
// Make a couple changes to the inputs
userEvent.type(screen.getByLabelText("text_field"), "new_value")
userEvent.click(screen.getByLabelText("bool_field"))
userEvent.type(screen.getByLabelText("text_field_with_default"), "!!!!")
userEvent.click(screen.getByLabelText("choice_field"))
userEvent.click(screen.getByText("choice1"))
userEvent.click(screen.getByText("choice3"))
// Click the submit button
userEvent.click(screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`))
// Wait for the button to be enabled again,
// which signals successful trigger button response
await waitFor(
() =>
expect(screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`)).not
.toBeDisabled
)
const calls = nonAnalyticsCalls()
expect(calls.length).toEqual(1)
const call = calls[0]
expect(call[0]).toEqual(
"/proxy/apis/tilt.dev/v1alpha1/uibuttons/TestButton/status"
)
expect(call[1]).toBeTruthy()
expect(call[1]!.method).toEqual("PUT")
expect(call[1]!.body).toBeTruthy()
const actualStatus: UIButtonStatus = JSON.parse(
call[1]!.body!.toString()
).status
const expectedStatus: UIButtonStatus = {
lastClickedAt: "2016-12-21T23:36:07.071000+00:00",
inputs: [
{
name: inputSpecs[0].name,
text: {
value: "new_value",
},
},
{
name: inputSpecs[1].name,
bool: {
value: true,
},
},
{
name: inputSpecs[2].name,
text: {
value: "default text!!!!",
},
},
{
name: inputSpecs[3].name,
hidden: {
value: inputSpecs[3].hidden!.value,
},
},
{
name: inputSpecs[4].name,
choice: {
value: "choice3",
},
},
],
}
expect(actualStatus).toEqual(expectedStatus)
})
it("submits default options when the submit button is clicked", async () => {
// The testing setup already includes a field with default text,
// so we can go ahead and click the submit button
userEvent.click(screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`))
// Wait for the button to be enabled again,
// which signals successful trigger button response
await waitFor(
() =>
expect(screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`)).not
.toBeDisabled
)
const calls = nonAnalyticsCalls()
expect(calls.length).toEqual(1)
const call = calls[0]
expect(call[0]).toEqual(
"/proxy/apis/tilt.dev/v1alpha1/uibuttons/TestButton/status"
)
expect(call[1]).toBeTruthy()
expect(call[1]!.method).toEqual("PUT")
expect(call[1]!.body).toBeTruthy()
const actualStatus: UIButtonStatus = JSON.parse(
call[1]!.body!.toString()
).status
const expectedStatus: UIButtonStatus = {
lastClickedAt: "2016-12-21T23:36:07.071000+00:00",
inputs: [
{
name: inputSpecs[0].name,
text: {},
},
{
name: inputSpecs[1].name,
bool: {
value: false,
},
},
{
name: inputSpecs[2].name,
text: {
value: "default text",
},
},
{
name: inputSpecs[3].name,
hidden: {
value: inputSpecs[3].hidden!.value,
},
},
{
name: inputSpecs[4].name,
choice: {
value: "choice1",
},
},
],
}
expect(actualStatus).toEqual(expectedStatus)
})
})
describe("local storage for input values", () => {
let uibutton: UIButton
let inputSpecs: UIInputSpec[]
beforeEach(() => {
inputSpecs = [
textFieldForUIButton("text1"),
boolFieldForUIButton("bool1"),
]
uibutton = oneUIButton({ inputSpecs })
// Store previous values for input fields
buttonInputsAccessor.set({
text1: "text value",
bool1: true,
})
customRender(<ApiButton uiButton={uibutton} />)
})
it("are read from local storage", () => {
// Open the options dialog
userEvent.click(
screen.getByLabelText(`Open ${uibutton.spec!.text!} options`)
)
expect(screen.getByLabelText("text1")).toHaveValue("text value")
expect(screen.getByLabelText("bool1")).toBeChecked()
})
it("are written to local storage when edited", () => {
// Open the options dialog
userEvent.click(
screen.getByLabelText(`Open ${uibutton.spec!.text!} options`)
)
// Type a new value in the text field
const textField = screen.getByLabelText("text1")
userEvent.clear(textField)
userEvent.type(textField, "new value!")
// Uncheck the boolean field
userEvent.click(screen.getByLabelText("bool1"))
// Expect local storage values are updated
expect(buttonInputsAccessor.get()).toEqual({
text1: "new value!",
bool1: false,
})
})
})
describe("button with only hidden inputs", () => {
let uibutton: UIButton
beforeEach(() => {
const inputSpecs = [1, 2, 3].map((i) =>
hiddenFieldForUIButton(`hidden${i}`, `value${i}`)
)
uibutton = oneUIButton({ inputSpecs })
customRender(<ApiButton uiButton={oneUIButton({ inputSpecs })} />)
})
it("doesn't render an options button", () => {
expect(
screen.queryByLabelText(`Open ${uibutton.spec!.text!} options`)
).not.toBeInTheDocument()
})
it("doesn't render any input elements", () => {
expect(screen.queryAllByRole("input").length).toBe(0)
})
})
describe("buttons that require confirmation", () => {
let uibutton: UIButton
let rerender: RenderResult["rerender"]
beforeEach(() => {
uibutton = oneUIButton({ requiresConfirmation: true })
rerender = customRender(<ApiButton uiButton={uibutton} />).rerender
})
it("displays 'confirm' and 'cancel' buttons after a single click", () => {
const buttonBeforeClick = screen.getByLabelText(
`Trigger ${uibutton.spec!.text!}`
)
expect(buttonBeforeClick).toBeInTheDocument()
expect(buttonBeforeClick).toHaveTextContent(uibutton.spec!.text!)
userEvent.click(buttonBeforeClick)
const confirmButton = screen.getByLabelText(
`Confirm ${uibutton.spec!.text!}`
)
expect(confirmButton).toBeInTheDocument()
expect(confirmButton).toHaveTextContent("Confirm")
const cancelButton = screen.getByLabelText(
`Cancel ${uibutton.spec!.text!}`
)
expect(cancelButton).toBeInTheDocument()
})
it("clicking the 'confirm' button triggers a button API call", async () => {
// Click the submit button
userEvent.click(screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`))
// Expect that it should not have submitted the click to the backend
expect(nonAnalyticsCalls().length).toEqual(0)
// Click the confirm submit button
userEvent.click(screen.getByLabelText(`Confirm ${uibutton.spec!.text!}`))
// Wait for the button to be enabled again,
// which signals successful trigger button response
await waitFor(
() =>
expect(screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`)).not
.toBeDisabled
)
// Expect that the click was submitted and the button text resets
expect(nonAnalyticsCalls().length).toEqual(1)
expect(
screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`)
).toHaveTextContent(uibutton.spec!.text!)
})
it("clicking the 'cancel' button resets the button", () => {
// Click the submit button
userEvent.click(screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`))
// Expect that it should not have submitted the click to the backend
expect(nonAnalyticsCalls().length).toEqual(0)
// Click the cancel submit button
userEvent.click(screen.getByLabelText(`Cancel ${uibutton.spec!.text!}`))
// Expect that NO click was submitted and the button text resets
expect(nonAnalyticsCalls().length).toEqual(0)
expect(
screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`)
).toHaveTextContent(uibutton.spec!.text!)
})
// This test makes sure that the `confirming` state resets if a user
// clicks a toggle button once, then navigates to another resource
// with a toggle button (which will have a different button name)
it("resets the `confirming` state when the button's name changes", () => {
// Click the button and verify the confirmation state
userEvent.click(screen.getByLabelText(`Trigger ${uibutton.spec!.text!}`))
expect(
screen.getByLabelText(`Confirm ${uibutton.spec!.text!}`)
).toBeInTheDocument()
expect(
screen.getByLabelText(`Cancel ${uibutton.spec!.text!}`)
).toBeInTheDocument()
// Then update the component's props with a new button
const anotherUIButton = oneUIButton({
buttonName: "another-button",
buttonText: "Click another button!",
requiresConfirmation: true,
})
rerender(<ApiButton uiButton={anotherUIButton} />)
// Verify that the button's confirmation state is reset
// and displays the new button text
const updatedButton = screen.getByLabelText(
`Trigger ${anotherUIButton.spec!.text!}`
)
expect(updatedButton).toBeInTheDocument()
expect(updatedButton).toHaveTextContent(anotherUIButton.spec!.text!)
})
})
describe("helper functions", () => {
describe("buttonsByComponent", () => {
it("returns an empty object if there are no buttons", () => {
expect(buttonsByComponent(undefined)).toStrictEqual(
new Map<string, ButtonSet>()
)
})
it("returns a map of resources names to button sets", () => {
const buttons = [
oneUIButton({ componentID: "frontend", buttonName: "Lint" }),
oneUIButton({ componentID: "frontend", buttonName: "Compile" }),
disableButton("frontend", true),
oneUIButton({ componentID: "backend", buttonName: "Random scripts" }),
disableButton("backend", false),
oneUIButton({ componentID: "data-warehouse", buttonName: "Flush" }),
oneUIButton({ componentID: "" }),
]
const expectedOutput = new Map<string, ButtonSet>([
[
"frontend",
{
default: [buttons[0], buttons[1]],
toggleDisable: buttons[2],
},
],
["backend", { default: [buttons[3]], toggleDisable: buttons[4] }],
["data-warehouse", { default: [buttons[5]] }],
])
expect(buttonsByComponent(buttons)).toStrictEqual(expectedOutput)
})
})
})
})