Skip to content

Latest commit

 

History

History
173 lines (126 loc) · 6.91 KB

testing.md

File metadata and controls

173 lines (126 loc) · 6.91 KB

Testing

Astro docs: Testing · Container API

End-to-end testing is unchanged: Playwright or Cypress against astro dev sees rendered HTML and does not care which language produced it.

What needs wiring is the other shape Astro offers — rendering one component in isolation with the Container API. The renderer works there unmodified; what it needs is a .NET host, because outside astro dev and astro build there is nothing running to execute your C#.

Rendering a C# component in a test

npm install --save-dev vitest
// src/components/Card.test.ts
import { afterAll, beforeAll, expect, test } from 'vitest';
import { createAstroSharpTestHost, type AstroSharpTestHost } from 'astrosharp/test';

let sharp: AstroSharpTestHost;

// The first call compiles your C#, so give it room. Later runs reuse the build output.
beforeAll(async () => { sharp = await createAstroSharpTestHost(); }, 120_000);

// Without this the .NET host outlives the run and the process never exits.
afterAll(() => sharp?.dispose());

test('a card renders its title', async () => {
  const container = await sharp.createContainer();

  const html = await container.renderToString(sharp.component('components/Card.razor'), {
    props: { title: 'Hello', count: 3 },
    slots: { default: '<strong>slot content</strong>' },
  });

  expect(html).toContain('Hello');
  expect(html).toContain('<strong>slot content</strong>');
});

No vitest.config.ts is required, and no getViteConfig. The helper starts the host itself, so a plain Vitest run is enough.

What it gives you

sharp.component(path) A component for renderToString, by source path.
sharp.createContainer() A container with the astrosharp renderer already registered.
sharp.componentPaths Every component the host discovered.
sharp.renderer The renderer itself, for a container you build yourself.
sharp.host The .NET host, for anything the above does not cover.
sharp.dispose() Stops it.

The path is matched leniently — components/Card.razor, src/components/Card.razor and ./src/components/Card.razor all find the same file. A name matching two components is refused rather than resolved to whichever came first, and a name matching none lists what there is.

Everything a component reads from the render context works: Astro.Props, Astro.Slots, Astro.Request, Astro.Url, Astro.Params and Astro.Locals all come from the options the container was given.

await container.renderToString(sharp.component('pages/greeting.razor'), {
  params: { locale: 'fr' },
  request: new Request('https://example.com/fr/greeting'),
  locals: { user: 'ada' },
});

Config-dependent components

Astro.I18n, Astro.Env and Astro.Meta are resolved from astro.config.mjs, which a container knows nothing about. Pass it in if the component under test reads one:

import config from '../astro.config.mjs';

sharp = await createAstroSharpTestHost({ astroConfig: config });

Leaving it out is not an error — an unconfigured Astro.I18n reports itself as unconfigured, which is a state the C# already models — so it is only worth passing when it matters.

Building the container yourself

createContainer() is a convenience over two lines. For container options of your own:

import { experimental_AstroContainer } from 'astro/container';

const container = await experimental_AstroContainer.create({ streaming: true });
container.addServerRenderer({ name: 'astrosharp', renderer: sharp.renderer });

The name is not arbitrary — Astro matches components against renderers by it.

Importing .razor directly

If you would rather write import Card from '../src/components/Card.razor' than name a path, that works too, with a Vitest config built from Astro's:

// vitest.config.ts
import { getViteConfig } from 'astro/config';

export default getViteConfig({ test: { globals: true } });
import { getContainerRenderer } from 'astrosharp/container-renderer';
import { loadRenderers } from 'astro:container';

const renderers = await loadRenderers([getContainerRenderer()]);
const container = await experimental_AstroContainer.create({ renderers });

This resolves the component through Vite, so Astro.Import, scoped styles and lifted <script> blocks all behave as they do on a real page. You still need createAstroSharpTestHost: it is what runs your C#. getViteConfig starts a host of its own while resolving the config, but that happens in the main process and your tests run in a worker, which has a globalThis of its own — so the host has to belong to the process doing the rendering. The two are safe together, because a component's id is a hash of its source path and the generated projects are kept in separate directories.

Limitations

A placement needs its module handed to you. A container has no Vite module graph, so a component that reaches for an .astro component with Astro.Import has nothing to resolve against and fails naming what is missing. Supply it:

import Badge from '../src/components/Badge.astro';

sharp.component('components/Hero.razor', { imports: { './Badge.astro': Badge } });

That import needs Astro's Vite plugin, so in practice this is the case for the getViteConfig setup above, where it resolves by itself.

A component's own <style> and <script> blocks are not in the rendered output. The build lifts them out and hands them to Vite, which is what puts them through Sass and PostCSS and hoists them into the page head — so the fragment a container returns carries the scope attribute but not the CSS:

<p data-ashp-15affd67 class="styled">styled</p>

That is the same markup a real page renders; on a page the stylesheet arrives separately. To assert on the CSS itself, read it off the manifest entry, where it sits already scoped:

expect(sharp.component('components/Styled.razor').__sharpEntry.inlineStyles?.[0])
  .toContain('data-ashp-');

The generated project lives in .astrosharp/test. Kept between runs so a second run is fast, and separate from .astrosharp so a test run and a dev server cannot contend for one MSBuild output directory. Delete it if a build ever goes strange; it is a cache.

The Container API is experimental. Astro says it is "subject to breaking changes, even in minor or patch releases". astrosharp/test is a thin layer over it and inherits that.

A container render is not an integration test. It exercises the renderer and your C#, and not the Vite plugin, the route table, the manifest, or the callback channel back into astro:content. For anything living in those seams, drive a real server — which is the choice this repository's own suite makes for itself, and for the same reason.