expectSnapshot function

Future<void> expectSnapshot(
  1. Trellis engine,
  2. String template,
  3. Map<String, dynamic> context, {
  4. required String goldenFile,
  5. String? fragment,
})

Renders a template file and compares the output against a golden file.

On first run (golden file does not exist), the golden file is auto-created and the test passes with an informational print message.

On subsequent runs, the rendered output is compared against the golden file. A mismatch causes a test failure with a readable diff showing expected vs actual content.

When TRELLIS_UPDATE_GOLDENS=true is set, the golden file is always overwritten with the current rendered output, and the test passes.

The goldenFile path is relative to the current working directory (typically the package root when running dart test). If a fragment is specified, only that fragment is rendered.

test('page snapshot', () async {
  await expectSnapshot(
    engine, 'page',
    {'title': 'Hello', 'items': ['A', 'B']},
    goldenFile: 'test/goldens/page.html',
  );
});

Implementation

Future<void> expectSnapshot(
  Trellis engine,
  String template,
  Map<String, dynamic> context, {
  required String goldenFile,
  String? fragment,
}) async {
  final String rendered;
  if (fragment != null) {
    rendered = await engine.renderFileFragment(template, fragment: fragment, context: context);
  } else {
    rendered = await engine.renderFile(template, context);
  }
  compareOrCreateGolden(normalizeHtml(rendered), goldenFile);
}