Skip to content

Commit

Permalink
Fix empty event.detail.options payload on removeAll (#266)
Browse files Browse the repository at this point in the history
* set selected = [] AFTER dispatching removeAll/change event

* test for expected event.detail.option(s) payload on CustomEvent dispatch
  • Loading branch information
janosh authored Sep 20, 2023
1 parent 58cee43 commit 4f362ed
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 19 deletions.
4 changes: 2 additions & 2 deletions src/lib/MultiSelect.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -348,10 +348,10 @@
}
function remove_all() {
selected = []
searchText = ``
dispatch(`removeAll`, { options: selected })
dispatch(`change`, { options: selected, type: `removeAll` })
selected = []
searchText = ``
}
$: is_selected = (label: string | number) => selected.map(get_label).includes(label)
Expand Down
49 changes: 32 additions & 17 deletions tests/unit/MultiSelect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1051,26 +1051,41 @@ test(`first matching option becomes active automatically on entering searchText`
})

test.each([
[`add`, `ul.options li`, mouseup],
[`change`, `ul.options li`, mouseup],
[`remove`, `ul.selected button.remove`, mouseup],
[`change`, `ul.selected button.remove`, mouseup],
[`removeAll`, `button.remove-all`, mouseup],
[`change`, `button.remove-all`, mouseup],
])(`bubbles <input> node DOM events`, async (event_name, selector, trigger) => {
const select = new MultiSelect({
target: document.body,
props: { options: [1, 2, 3], selected: [1, 2] },
})
[`add`, `ul.options li`],
[`change`, `ul.options li`],
[`remove`, `ul.selected button.remove`],
[`change`, `ul.selected button.remove`],
[`removeAll`, `button.remove-all`],
[`change`, `button.remove-all`],
])(
`fires %s event with expected payload when clicking %s`,
async (event_name, selector, trigger = mouseup) => {
const select = new MultiSelect({
target: document.body,
props: { options: [1, 2, 3], selected: [1, 2] },
})

const spy = vi.fn()
select.$on(event_name as keyof MultiSelectEvents, spy)
const is_event = (name: string, event: CustomEvent) =>
name === event_name ||
(event_name === `change` && event.detail.type === name)

const spy = vi.fn((event) => {
if (is_event(`removeAll`, event)) {
expect(event.detail.options).toEqual([1, 2])
} else if (is_event(`remove`, event)) {
expect(event.detail.option).toEqual(1)
} else if (is_event(`add`, event)) {
expect(event.detail.option).toEqual(3)
}
})
select.$on(event_name as keyof MultiSelectEvents, spy)

doc_query(selector).dispatchEvent(trigger)
await tick()
doc_query(selector).dispatchEvent(trigger)
await tick()

expect(spy, `event type '${event_name}'`).toHaveBeenCalledTimes(1)
})
expect(spy, `event type '${event_name}'`).toHaveBeenCalledTimes(1)
},
)

describe.each([
[true, (opt: Option) => opt],
Expand Down

0 comments on commit 4f362ed

Please sign in to comment.