Mocking & Spying
@stencil/vitest provides a powerful spy system that lets you observe and control component behavior during tests. You can spy on methods, props, and lifecycle hooks to verify behavior without modifying your component code.
Setup Requirement
The spy system patches customElements.define, so components must be registered after the test framework initializes. A test file that imports its components, as in the standard setup, already does this.
If you load your built output from a setup file instead, do it in a beforeAll block:
// vitest-setup.ts
- await import('./dist/loader-bundle/test-components/test-components.js');
+ import { beforeAll } from 'vitest';
+ beforeAll(async () => {
+ await import('./dist/loader-bundle/test-components/test-components.js');
+ });
Mocking Modules
Components are compiled from source, so Vitest's vi.mock() can replace a module that a component imports. Import vi from vitest itself here, as vi.mock() isn't recognized when it comes from another package:
import { render } from '@stencil/vitest';
import { vi, it, expect } from 'vitest';
vi.mock('./format', () => ({
formatLabel: (label: string) => `mocked:${label}`,
}));
import './my-button';
it('uses the mocked module', async () => {
const { root } = await render(<my-button label="Save" />);
expect(root.shadowRoot?.querySelector('button')?.textContent).toBe('mocked:Save');
});
Method Spying
Spy on methods while still calling the original implementation:
import { render, describe, it, expect } from '@stencil/vitest';
describe('my-button', () => {
it('calls handleClick when clicked', async () => {
const { root, spies } = await render(<my-button>Click me</my-button>, {
spyOn: {
methods: ['handleClick'],
},
});
// Trigger the method
root.shadowRoot?.querySelector('button')?.click();
// Assert the method was called
expect(spies?.methods.handleClick).toHaveBeenCalledTimes(1);
expect(spies?.methods.handleClick).toHaveBeenCalledWith(
expect.objectContaining({ type: 'click' })
);
// Reset call history
spies?.methods.handleClick.mockClear();
});
});