Skip to content

Commit

Permalink
fix: emit error events from <NuxtImg> placeholder (#1640)
Browse files Browse the repository at this point in the history
  • Loading branch information
jianxing-xu authored Dec 20, 2024
1 parent 2edb715 commit 5fd221a
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/runtime/components/NuxtImg.vue
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,10 @@ onMounted(() => {
emit('load', event)
}
img.onerror = (event) => {
emit('error', event)
}
markFeatureUsage('nuxt-image')
return
Expand Down
27 changes: 27 additions & 0 deletions test/unit/image.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,15 +160,20 @@ describe('Renders simple image', () => {

const getImageLoad = (cb = () => {}) => {
let resolve = () => {}
let reject = () => {}
let image = {} as HTMLImageElement
const loadEvent = Symbol('loadEvent')
const errorEvent = Symbol('errorEvent')
const ImageMock = vi.fn(() => {
const _image = {
onload: () => {},
onerror: () => {},
} as unknown as HTMLImageElement
image = _image
// @ts-expect-error not valid argument for onload
resolve = () => _image.onload?.(loadEvent)
// @ts-expect-error not valid argument for onload
reject = () => _image.onerror?.(errorEvent)

return _image
})
Expand All @@ -179,8 +184,10 @@ const getImageLoad = (cb = () => {}) => {

return {
resolve,
reject,
image,
loadEvent,
errorEvent,
}
}

Expand Down Expand Up @@ -280,6 +287,26 @@ describe('Renders placeholder image', () => {
`)
expect(wrapper.element.getAttribute('src')).toMatchInlineSnapshot(`"/_ipx/_/image.png"`)
})

it('props.placeholder with source loaded error event triggers', async () => {
const {
reject: rejectImage,
errorEvent,
} = getImageLoad(() => {
wrapper = mount(NuxtImg, {
propsData: {
width: 200,
height: 200,
src,
placeholder: true,
},
})
})
rejectImage()
await nextTick()

expect(wrapper.emitted().error![0]).toStrictEqual([errorEvent])
})
})

describe('Renders image, applies module config', () => {
Expand Down

0 comments on commit 5fd221a

Please sign in to comment.