---
url: https://paperpic.dev/guide/testing.md
description: >-
  How to test an app that uses PaperPic, with a stand-in in jsdom or happy-dom
  and the real viewer in a browser with Playwright. JavaScript, Vue and React.
---

# 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 {#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()`](../reference/methods#getstate) returns `status: 'error'`, and [`error`](../reference/events#error) arrives with `phase: 'load'`.
* jsdom fails sooner. It has no `ResizeObserver`, so mounting throws `ReferenceError: ResizeObserver is not defined`. With a stub of `ResizeObserver` you get as far as in happy-dom, and jsdom adds a `Not implemented: HTMLCanvasElement's getContext() method` warning.

Either way, no user could ever get to Apply there, so the test sends `apply` itself.

## A stand-in in unit tests {#stand-in}

The tests below cover the code of [Upload to a server](../examples/upload): 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.

:::tabs key:framework
\== JavaScript

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`:

```ts
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')
})
```

\== Vue

With `stubs`, Vue Test Utils renders an empty component where PaperPic would be, and the test emits `apply` from it, as the viewer would:

```ts
import { PaperPic } from '@paperpic/vue'
import { mount } from '@vue/test-utils'
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 = mount(Invoice, {
    global: {
      stubs: { PaperPic: true },
    },
  })

  wrapper.findComponent(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' }))
})
```

\== React

`vi.mock()` swaps PaperPic for a plain button that sends `apply` with a tiny image, and Testing Library clicks it:

```tsx
import type { ExportedImage } from '@paperpic/react'
import { fireEvent, render, screen } from '@testing-library/react'
import { expect, it, vi } from 'vitest'
import { Invoice } from './Invoice'

// PaperPic needs a real browser. In its place, a button applies a small image
vi.mock('@paperpic/react', () => ({
  PaperPic: ({ onApply }: { onApply?: (image: ExportedImage) => void }) => (
    <button
      type="button"
      onClick={() => onApply?.({
        blob: new Blob(['png']),
        type: 'image/png',
        width: 1,
        height: 1,
      })}
    >
      Apply
    </button>
  ),
}))

it('saves the edited invoice', async () => {
  const fetch = vi.fn(async () => new Response(null, { status: 204 }))
  vi.stubGlobal('fetch', fetch)
  render(<Invoice />)

  fireEvent.click(screen.getByRole('button', { name: 'Apply' }))

  await screen.findByText('Saved')
  expect(fetch).toHaveBeenCalledWith('/api/documents/42', expect.objectContaining({ method: 'PUT' }))
})
```

:::

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`](../reference/types#exportedimage) lists everything that `apply` carries.

## In Nuxt {#nuxt}

In Nuxt, unit tests run with [`@nuxt/test-utils`](https://nuxt.com/docs/getting-started/testing), 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](../reference/nuxt) page explains:

```ts
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 {#browser}

In a browser, the viewer runs for real: it loads the image, edits it in the worker and applies the changes. This [Playwright](https://playwright.dev) test opens the invoice, rotates it, applies the changes and waits for the upload:

```ts
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-control` rather than by their names. The names change with the language and with [`labels`](../reference/options#labels), and these values don't. [Controls](../reference/css-tokens#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](../examples/attach-and-scan) does, hand the file input a file with `setInputFiles()`.
* To test your server too, take out `page.route()`.
