|
| 1 | +--- |
| 2 | +'@builder.io/qwik-city': patch |
| 3 | +--- |
| 4 | + |
| 5 | +feat: allow mocking loaders in QwikCityMockProvider |
| 6 | + |
| 7 | + |
| 8 | +> If you are using `routeLoader$`s in a Qwik Component that you want to test, you can provide a `loaders` prop to mock the data returned by the loaders |
| 9 | +
|
| 10 | +```ts title="src/loaders/product.loader.ts" |
| 11 | +import { routeLoader$ } from '@builder.io/qwik-city'; |
| 12 | + |
| 13 | +export const useProductData = routeLoader$(async () => { |
| 14 | + const res = await fetch('https://.../product'); |
| 15 | + const product = (await res.json()) as Product; |
| 16 | + return product; |
| 17 | +}); |
| 18 | +``` |
| 19 | + |
| 20 | +```tsx title="src/components/product.tsx" |
| 21 | +import { component$ } from '@builder.io/qwik'; |
| 22 | + |
| 23 | +import { useProductData } from '../loaders/product.loader'; |
| 24 | + |
| 25 | +export const Footer = component$(() => { |
| 26 | + const signal = useProductData(); |
| 27 | + return <footer>Product name: {signal.value.product.name}</footer>; |
| 28 | +}); |
| 29 | +``` |
| 30 | + |
| 31 | +```tsx title="src/components/product.spec.tsx" |
| 32 | +import { createDOM } from '@builder.io/qwik/testing'; |
| 33 | +import { test, expect } from 'vitest'; |
| 34 | + |
| 35 | +import { Footer } from './product'; |
| 36 | +import { useProductData } from '../loaders/product.loader'; |
| 37 | + |
| 38 | +test('should render footer with product name', async () => { |
| 39 | + const { screen, render } = await createDOM(); |
| 40 | + const loadersMock = [ |
| 41 | + { |
| 42 | + loader: useProductData, |
| 43 | + data: { product: { name: 'Test Product' } }, |
| 44 | + }, |
| 45 | + ]; |
| 46 | + await render( |
| 47 | + <QwikCityMockProvider loaders={loadersMock}> |
| 48 | + <Footer /> |
| 49 | + </QwikCityMockProvider>, |
| 50 | + ); |
| 51 | + expect(screen.innerHTML).toMatchSnapshot(); |
| 52 | +}); |
| 53 | +``` |
0 commit comments