Skip to content

Commit 656adc2

Browse files
authored
Merge pull request #119 from vuejs/fix/add-parameter-to-emit
fix: Allow passing an event name to the `emitted` method
2 parents e6586be + d4f2070 commit 656adc2

File tree

3 files changed

+42
-4
lines changed

3 files changed

+42
-4
lines changed

src/vue-wrapper.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,10 +68,14 @@ export class VueWrapper<T extends ComponentPublicInstance> {
6868
return true
6969
}
7070

71-
emitted(): Record<string, unknown[]> {
72-
// TODO Should we define this?
73-
// @ts-ignore
74-
return this.vm.__emitted
71+
emitted<T = unknown>(): Record<string, T[]>
72+
emitted<T = unknown>(eventName?: string): T[]
73+
emitted<T = unknown>(eventName?: string): T[] | Record<string, T[]> {
74+
if (eventName) {
75+
const emitted = (this.vm['__emitted'] as Record<string, T[]>)[eventName]
76+
return emitted
77+
}
78+
return this.vm['__emitted'] as Record<string, T[]>
7579
}
7680

7781
html() {

test-dts/wrapper.d-test.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,15 @@ expectType<SVGLineElement | undefined>(lineArray[0].element)
6161
byClassArray = domWrapper.findAll('.todo')
6262
expectType<Element | undefined>(byClassArray[0].element)
6363

64+
// emitted
65+
// event name
66+
let incrementEvent = wrapper.emitted<{ count: number }>('increment')
67+
expectType<{ count: number }>(incrementEvent[0])
68+
69+
// without event name
70+
let allEvents = wrapper.emitted()
71+
expectType<Record<string, unknown[]>>(allEvents)
72+
6473
// get
6574
// HTML element selector
6675
let input = wrapper.get('input')

tests/emit.spec.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,4 +96,29 @@ describe('emitted', () => {
9696
wrapper.find('button').trigger('click')
9797
expect(wrapper.emitted().parent[1]).toEqual(['foo', 'bar'])
9898
})
99+
100+
it('should allow passing the name of an event', () => {
101+
const Component = defineComponent({
102+
name: 'ContextEmit',
103+
104+
setup(props, ctx) {
105+
return () =>
106+
h('div', [
107+
h('button', { onClick: () => ctx.emit('hello', 'foo', 'bar') })
108+
])
109+
}
110+
})
111+
const wrapper = mount(Component)
112+
113+
// test what happens if you pass a none existent event
114+
expect(wrapper.emitted('hello')).toEqual(undefined)
115+
116+
wrapper.find('button').trigger('click')
117+
expect(wrapper.emitted('hello')[0]).toEqual(['foo', 'bar'])
118+
119+
wrapper.find('button').trigger('click')
120+
expect(wrapper.emitted('hello')[1]).toEqual(['foo', 'bar'])
121+
122+
expect(wrapper.emitted('hello')).toHaveLength(2)
123+
})
99124
})

0 commit comments

Comments
 (0)