Testing
Unit tests usually run in jsdom or happy-dom, which imitate a browser inside Node. That is fine for your own code, but not for PaperPic: it decodes images, draws them on a canvas and edits them in a Web Worker, and neither of them has any of that. So split the work. In unit tests, put a stand-in where PaperPic goes and check what your code does with the result. Test the editing itself in a real browser.
In jsdom and happy-dom
If you mount the real viewer there anyway, this is what you get:
- happy-dom shows the toolbar, but the image never loads:
getState()returnsstatus: 'error', anderrorarrives withphase: 'load'. - jsdom fails sooner. It has no
ResizeObserver, so mounting throwsReferenceError: ResizeObserver is not defined. With a stub ofResizeObserveryou get as far as in happy-dom, and jsdom adds aNot implemented: HTMLCanvasElement's getContext() methodwarning.
Either way, no user could ever get to Apply there, so the test sends apply itself.
A stand-in in unit tests
The tests below cover the code of Upload to a server: once the user applies the changes, it uploads the image and shows Saved. They run in Vitest with jsdom or happy-dom, and replace fetch, so nothing goes over the network.
Move the code of the example into a function that creates the viewer and returns it, such as showInvoice(viewer, status) in show-invoice.ts. vi.mock() swaps PaperPic for a class that only keeps the listeners, so the test can call the one for apply:
import { expect, it, vi } from 'vitest'
import { showInvoice } from './show-invoice'
// The listeners that the code adds, kept so the test can call them
const listeners = vi.hoisted(() => new Map<string, (payload: unknown) => unknown>())
vi.mock('@paperpic/core', () => ({
PaperPic: class {
on(name: string, listener: (payload: unknown) => unknown) {
listeners.set(name, listener)
return () => listeners.delete(name)
}
destroy() {}
},
}))
it('saves the edited invoice', async () => {
const fetch = vi.fn(async () => new Response(null, { status: 204 }))
vi.stubGlobal('fetch', fetch)
const status = document.createElement('p')
showInvoice(document.createElement('div'), status)
await listeners.get('apply')?.({
blob: new Blob(['png']),
type: 'image/png',
width: 1,
height: 1,
})
expect(fetch).toHaveBeenCalledWith('/api/documents/42', expect.objectContaining({ method: 'PUT' }))
expect(status.textContent).toBe('Saved')
})The image needs no real pixels: a Blob of a few bytes is enough, because your code only looks at its type and size. ExportedImage lists everything that apply carries.
In Nuxt
In Nuxt, unit tests run with @nuxt/test-utils, in the nuxt environment of Vitest. That environment runs on happy-dom, or on jsdom if you choose it, so PaperPic still needs a stand-in. It works as in Vue, with two changes. mountSuspended() takes the place of mount() and mounts the component inside your Nuxt app. And since @paperpic/nuxt registers PaperPic for you, your component does not import it, so the test finds it by its name. This test covers the same component, saved as Invoice.vue and adapted to Nuxt as the Nuxt page explains:
import { mountSuspended } from '@nuxt/test-utils/runtime'
import { expect, it, vi } from 'vitest'
import Invoice from './Invoice.vue'
it('saves the edited invoice', async () => {
const fetch = vi.fn(async () => new Response(null, { status: 204 }))
vi.stubGlobal('fetch', fetch)
// A stub takes the place of PaperPic, which needs a real browser
const wrapper = await mountSuspended(Invoice, {
global: {
stubs: { PaperPic: true },
},
})
wrapper.findComponent({ name: 'PaperPic' }).vm.$emit('apply', {
blob: new Blob(['png']),
type: 'image/png',
width: 1,
height: 1,
})
await vi.waitFor(() => expect(wrapper.text()).toContain('Saved'))
expect(fetch).toHaveBeenCalledWith('/api/documents/42', expect.objectContaining({ method: 'PUT' }))
})In a real browser
In a browser, the viewer runs for real: it loads the image, edits it in the worker and applies the changes. This Playwright test opens the invoice, rotates it, applies the changes and waits for the upload:
import { expect, test } from '@playwright/test'
test('saves the edited invoice', async ({ page }) => {
// data-paperpic-control is the same in every language. The toolbar and the edit bar both have a rotateLeft,
// and the toolbar is hidden while editing, so the locator keeps the visible one
const control = (name: string) => page.locator(`[data-paperpic-control="${name}"]`).filter({ visible: true })
// Answers the upload, so the test needs no server
await page.route('**/api/documents/42', route => route.fulfill({ status: 204 }))
await page.goto('/invoices/42')
// Edit is enabled once the image is on display
await expect(control('edit')).toBeEnabled()
await control('edit').click()
await control('rotateLeft').click()
const saved = page.waitForRequest(request => request.method() === 'PUT' && request.url().endsWith('/api/documents/42'))
await control('apply').click()
await saved
await expect(page.getByText('Saved')).toBeVisible()
})- Find the controls by
data-paperpic-controlrather than by their names. The names change with the language and withlabels, and these values don't. Controls lists them all. - A rotation is the quickest edit to test, because nothing has to wait. Straighten looks for the document first, and its Done button stays disabled until it finds one or the user moves a corner.
- To start from a photo, as Attach and scan does, hand the file input a file with
setInputFiles(). - To test your server too, take out
page.route().