Skip to content

Testing with vue-leaflet ​

When testing components built with vue-leaflet, you typically encounter two scenarios:

  1. Component Testing in an Application: Testing your own Vue components that render maps and layers.
  2. Plugin & Custom Layer Authoring: Testing custom Leaflet wrappers, plugins, or extensions that interact with vue-leaflet's internal injection hierarchy.

vue-leaflet provides testing helpers and utilities for both via the @maxel01/vue-leaflet/tests subpath.


1. Unit Testing in Applications ​

When unit testing Vue components that use vue-leaflet in headless browser environments like JSDOM (used by Vitest or Jest), Leaflet requires several browser APIs that JSDOM does not provide out of the box:

  • ResizeObserver
  • window.matchMedia
  • Non-zero dimensions for DOM elements (clientWidth / clientHeight)

Without these mocks, Leaflet will throw errors during test execution (such as ReferenceError: ResizeObserver is not defined).

Setup Test Environment (setupVueLeafletTest) ​

Call setupVueLeafletTest() in your global test setup file (e.g. tests/setup.ts in Vitest or setupFilesAfterEnv in Jest):

ts
import { setupVueLeafletTest } from '@maxel01/vue-leaflet/tests'

// Sets up ResizeObserver, window.matchMedia, and default element dimensions
setupVueLeafletTest()

Options ​

setupVueLeafletTest accepts an optional options object to configure the mock element dimensions:

ts
setupVueLeafletTest({
    width: 600,  // Default clientWidth (default: 300)
    height: 400  // Default clientHeight (default: 300)
})

Example Component Test ​

vue
<!-- MapComponent.vue -->
<script setup>
import { LMap, LTileLayer } from '@maxel01/vue-leaflet'
</script>

<template>
  <div style="height: 400px; width: 600px">
    <LMap :zoom="2" :center="[47.41, -1.22]">
      <LTileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
    </LMap>
  </div>
</template>
ts
// MapComponent.spec.ts
import { describe, it, expect } from 'vitest'
import { mount } from '@vue/test-utils'
import { setupVueLeafletTest } from '@maxel01/vue-leaflet/tests'
import MapComponent from './MapComponent.vue'

// If not called in a global setup file, call it at the top of your test file:
setupVueLeafletTest()

describe('MapComponent', () => {
    it('renders and mounts properly', () => {
        const wrapper = mount(MapComponent)
        expect(wrapper.exists()).toBe(true)
    })
})

2. Testing Utilities for Plugin Authors ​

@maxel01/vue-leaflet/tests exports pre-configured component wrappers, lifecycle assertions, and mock injection functions for testing custom components, extensions, or plugins in isolation.

Component Wrappers ​

Leaflet components require parent injection keys (e.g. addLayer, removeLayer). Wrapper factories mount components with these injections pre-configured:

ts
import { createMarkerWrapper } from '@maxel01/vue-leaflet/tests'

const wrapper = await createMarkerWrapper({
    latLng: [44.5, 11.5]
})

const marker = wrapper.vm.leafletObject

Lifecycle Assertions ​

Standardized test suites allow testing common Leaflet component lifecycle patterns:

ts
import { describe } from 'vitest'
import {
    createMarkerWrapper,
    testEmitsReady,
    testRemoveOnUnmount
} from '@maxel01/vue-leaflet/tests'

describe('CustomMarker', () => {
    const getWrapper = () => createMarkerWrapper({ latLng: [45, 10] })

    // Asserts that the component emits 'ready' with its leafletObject on mount:
    testEmitsReady(getWrapper)

    // Asserts that leafletObject.remove() is called when the component is unmounted:
    testRemoveOnUnmount(getWrapper)
})

Prop Binding Tests ​

You can test that updating Vue props propagates to Leaflet setters using testPropsBindingToLeaflet:

ts
import { describe } from 'vitest'
import {
    createMarkerWrapper,
    testPropsBindingToLeaflet
} from '@maxel01/vue-leaflet/tests'
import { LatLng } from 'leaflet'

describe('LMarker prop bindings', () => {
    testPropsBindingToLeaflet(createMarkerWrapper, {
        zIndexOffset: 10,
        latLng: new LatLng(45.0, 10.0)
    })
})

📚 Test Utilities API Reference ​

The following utilities and helpers are automatically exported from @maxel01/vue-leaflet/tests:

🛠️ Environment Setup ​

Helpers to initialize headless browser testing environments (JSDOM) for Leaflet.

ExportDescriptionType / Signature
setupVueLeafletTestSets up polyfills and mocks required by Leaflet in Node/JSDOM test environments (Vitest/Jest). Mocks: - globalThis.ResizeObserver - window.matchMedia - HTMLElement.prototype.clientWidth / clientHeight(options: VueLeafletTestOptions = {}) => void
VueLeafletTestOptionsConfiguration options for setupVueLeafletTest.{ width?: number; height?: number }

📦 Component Wrappers ​

Factory functions that mount components in isolation with pre-configured mock injections.

ExportDescriptionType / Signature
createMapWrapperMounts an LMap component with default test dimensions (300px x 300px).(props?: {}, slots?: {}) => Promise<VueWrapper<any, any>>
createMarkerWrapperMounts an LMarker component with default coordinates and mocked parent layer injections.(props?: {}, slots?: {}) => Promise<VueWrapper<any, any>>

🧪 Lifecycle & Event Assertions ​

Standardized test suites for testing common Leaflet component lifecycle hooks and events.

ExportDescriptionType / Signature
testAddLayerAsserts that the layer is added to the parent via the mockAddLayer injection on mount.(getWrapper: () => Promise<VueWrapper<any>>) => void
testBindPopupAsserts that the popup is bound on mount via the bindPopup injection.(getWrapper: () => Promise<VueWrapper<any>>) => void
testBindTooltipAsserts that the tooltip is bound on mount via the bindTooltip injection.(getWrapper: () => Promise<VueWrapper<any>>) => void
testCanSetParentHtmlAsserts that the component checks canSetParentHtml injection on mount.(getWrapper: () => Promise<VueWrapper<any>>) => void
testControlLayerRegistrationAsserts that the layer control registers itself via the mockRegisterLayerControl injection on mount.(getWrapper: () => Promise<VueWrapper<any>>) => void
testControlRegistrationAsserts that the control registers itself via the mockRegisterControl injection on mount.(getWrapper: () => Promise<VueWrapper<any>>) => void
testEmitsReadyAsserts that the component emits the "ready" event with its Leaflet object on mount.(getWrapper: () => Promise<VueWrapper<any>>) => void
testHideLayerAsserts that the layer is hidden via the mockHideLayer injection.(getWrapper: () => Promise<VueWrapper<any>>) => void
testPropsBindingToLeafletAsserts that updating component props invokes the corresponding Leaflet setter on leafletObject.(getWrapper: (initialProps?: Record<string, any>) => Promise<VueWrapper<any>>, updatedProps: Record<string, any>) => void
testRegistrationAsserts that the component registers itself with the specified mock injection on mount.(getWrapper: () => Promise<VueWrapper<any>>, mockRegister: Mock) => void
testRemoveLayerAsserts that the layer is removed from the parent via the mockRemoveLayer injection on unmount.(getWrapper: () => Promise<VueWrapper<any>>) => void
testRemoveLayerOnUnmountAsserts that the layer removal injection (removeLayer) is called when the component is unmounted.(getWrapper: () => Promise<VueWrapper<any>>) => void
testRemoveOnUnmountAsserts that leafletObject.remove() is called when the component is unmounted.(getWrapper: () => Promise<VueWrapper<any>>) => void
testSetIconAsserts that the component sets the icon via setIcon injection.(getWrapper: () => Promise<VueWrapper<any>>) => void
testSetParentHtmlAsserts that the component sets parent HTML via setParentHtml injection.(getWrapper: () => Promise<VueWrapper<any>>) => void
testUnbindPopupOnUnmountAsserts that the popup is unbound on unmount via the unbindPopup injection.(getWrapper: () => Promise<VueWrapper<any>>) => void
testUnbindTooltipOnUnmountAsserts that the tooltip is unbound on unmount via the unbindTooltip injection.(getWrapper: () => Promise<VueWrapper<any>>) => void

⚡ Reactivity & Prop Binding Helpers ​

Utilities to assert synchronization between Vue reactive props and Leaflet setters.

ExportDescriptionType / Signature
mergeReactivePropsMerges parent and child reactive props test definitions including custom expecting handlers.(parentProps: P, childProps: C) => P & C
testComponentPropBindingsAsserts that Vue watchers are registered for every reactive/initOnly prop defined on the component.(getWrapper: () => Promise<VueWrapper<any>>, componentName: string) => void

🎭 Mock Injections ​

Pre-configured Vitest mock functions for Vue injection keys (e.g. addLayer, removeLayer).

ExportDescriptionType / Signature
mockAddLayerMock injection for adding a layer to a parent container (addLayerKey).Mock
mockBindPopupMock injection for binding a popup to a layer (bindPopupKey).Mock
mockBindTooltipMock injection for binding a tooltip to a layer (bindTooltipKey).Mock
mockCanSetParentHtmlInjectionMock injection returning whether parent HTML can be set (canSetParentHtmlKey).Mock
mockHideLayerMock injection for hiding a layer (hideLayerKey).Mock
mockRegisterControlMock injection for registering a control (registerControlKey).Mock
mockRegisterLayerControlMock injection for registering a layer control (registerLayerControlKey).Mock
mockRemoveLayerMock injection for removing a layer from a parent container (removeLayerKey).Mock
mockSetIconInjectionMock injection for setting an icon on a parent marker (setIconKey).Mock
mockSetParentHtmlInjectionMock injection for setting parent HTML (setParentHtmlKey).Mock
mockUnbindPopupMock injection for unbinding a popup from a layer (unbindPopupKey).Mock
mockUnbindTooltipMock injection for unbinding a tooltip from a layer (unbindTooltipKey).Mock

🗺️ Geo & Coordinate Helpers ​

Helpers for comparing Leaflet coordinates and bounds.

ExportDescriptionType / Signature
expectBoundsToBeCloseAsserts that two LatLngBounds are numerically close within the specified decimal digits.(first: LatLngBounds, second: LatLngBounds, numDigits: number | number[]) => void