@nera-static/test-utils

The shared test helpers, test suites and the canonical vitest config for the Nera static site generator's plugins, themes, starters and tools. Every Nera repo tests the same way with it: a throwaway site in a temp directory, built by the real engine, checked with the same readers, and the same standard cases for template publishing and theme contracts.
📖 Documentation: nera.js.org · Style guide: nera.js.org/docs/style-guide
It is a devDependency only. Nothing a plugin, theme, starter or site ships at runtime may import it.
🚀 Installation
npm install --save-dev @nera-static/test-utils vitest
Add the engine or the CLI only when your tests need them:
npm install --save-dev @nera-static/core # buildSite, parseYaml, loadYaml, frontmatter, the theme suites that read YAML
npm install --save-dev @nera-static/nera # nera(), scaffoldStarter, expectCleanBuild, buildVariants, themeGlobalSetup
| Peer dependency |
Range |
Needed by |
vitest |
^5.0.0 |
everything (required) |
@nera-static/core |
^4.15.0 (optional) |
buildSite, parseYaml, loadYaml, frontmatter, contractSuite, tokensSuite |
@nera-static/nera |
^1.11.0 (optional) |
nera, scaffoldStarter, expectCleanBuild, buildVariants, themeGlobalSetup |
No module imports core or the CLI when it is loaded: a helper that needs one resolves it on its first call, from where npm installed it beside this package, and names the install command when it is missing. The YAML helpers use core's own yaml package, so a test parses exactly as the build does.
Two runtime dependencies: cheerio, for $ and jsonLd, because they need a real HTML parser (attributes in any order, nested markup), which the regular-expression readers below deliberately are not; and @nera-static/plugin-utils ^1.8.0, whose isPlainObject and escapeRegExp the option checks and suites use, and whose FRONTMATTER_OPTIONS and splitFrontmatter frontmatter uses, so the fleet's generic helpers exist once. An option documented as an object must be a plain one (a literal, parsed YAML or Object.create(null)); a Map or a class instance throws like any other wrong value.
Requires Node.js 22.12.0 or later, like @nera-static/core, @nera-static/nera and @nera-static/validate. ESM only.
Entry points
| Import |
Holds |
@nera-static/test-utils |
the helpers and publishTemplateSuite |
@nera-static/test-utils/theme |
fixture mirrors, variant builds, the theme globalSetup and the six theme suites |
@nera-static/test-utils/vitest |
neraConfig, the canonical vitest config |
⚙️ The vitest config
// vitest.config.js
import { neraConfig } from '@nera-static/test-utils/vitest'
export default neraConfig()
neraConfig(test = {}) returns defineConfig({ test }) with the canonical test block, CANONICAL_TEST (also exported):
{
include: ['test/**/*.test.js'],
environment: 'node',
restoreMocks: true,
unstubEnvs: true,
unstubGlobals: true,
}
The keys you pass are merged over it, shallowly: a key you pass replaces the canonical value. Only add what the repo needs, with a comment saying why:
export default neraConfig({
// every test builds a site with the real CLI
testTimeout: 60000,
globalSetup: ['test/global-setup.js'],
})
Anything but a plain object throws a TypeError. restoreMocks is what puts captureConsole and useSiteCwd back after each test, so keep it.
🧰 Helpers
All from @nera-static/test-utils. Every helper checks its arguments and throws a message that says what it got and what to pass.
Files
tempDir(prefix = 'nera-test-') → string
A fresh directory under os.tmpdir(), as its real path (/private/var/… on macOS, so it agrees with process.cwd() inside it). Removed after the test file, in an afterAll registered when the package loads. The prefix must not contain a path separator.
- Called outside a test file (a
globalSetup, a script), the directory is not removed; remove it in your teardown.
- With
isolate: false in the vitest config only the first test file's directories are removed.
writeFiles(root, files) → root
Writes { 'relative/path': content } below the absolute root, creating parent directories. content is a string or a Buffer/Uint8Array; null removes the file or directory at that path (no error when it is already gone). A path that leaves root throws.
listFiles(dir, extensions?) → string[]
Every file below dir, recursively, as sorted relative paths with / separators on every platform. extensions (['.html', '.css']) keeps only those; without it, all files.
captureConsole(method) → () => string[]
Silences console[method] ('log', 'info', 'warn', 'error' or 'debug') with a vi.spyOn and returns a function giving the lines written so far, each call's arguments joined with a space (console.warn('⚠️ x:', 'msg') → '⚠️ x: msg'). Restored after the test by restoreMocks.
YAML
These need @nera-static/core and use its yaml package.
parseYaml(text) → unknown
Parses YAML text as core reads config/*.yaml. null for an empty document.
loadYaml(file) → unknown
Reads and parses a YAML file. A parse error names the file.
frontmatter(file) → object
A Markdown page's frontmatter, found and parsed as core does: the block between a --- first line and the next --- line (or the end of the file), with core's options (unquoted dates become Date objects, << merge keys work, a repeated key takes the last value). Fence rule and options are splitFrontmatter and FRONTMATTER_OPTIONS from @nera-static/plugin-utils/frontmatter, the parser is core's yaml. {} when the page has none. A parse error names the file.
Sites
makeSite({ files = {}, plugins = {} } = {}) → string
A throwaway Nera site in a tempDir, removed after the test file. It starts with:
| File |
Content |
package.json |
{ "name": "demo", "private": true, "type": "module" } |
config/app.yaml |
name: Demo, lang: en, origin: https://example.com/ |
views/layout.pug |
a page that renders content into main |
There is no default page: name your pages in files. files adds to the defaults or replaces them; null removes one. Each plugins entry { name: entryFile } (an absolute path to an existing file) becomes the local plugin plugins/<name>/index.js, re-exporting your entry file, so core loads the plugin under test the way a site loads its own plugins.
import path from 'node:path'
import { beforeAll, expect, it } from 'vitest'
import { buildSite, makeSite, readPublic } from '@nera-static/test-utils'
const ENTRY = path.resolve(import.meta.dirname, '../index.js')
let site
let result
beforeAll(async () => {
site = makeSite({
plugins: { sitemap: ENTRY },
files: { 'pages/index.md': '---\nlayout: layout.pug\n---\n# Home\n' },
})
result = await buildSite(site)
})
it('lists the home page', () => {
expect(readPublic(site, 'sitemap.xml')).toContain('<loc>https://example.com/index.html</loc>')
expect(result.warnings).toEqual([])
})
folders(root) → { config, pages, views, assets, dist, plugins }
The absolute folders core's run() takes for the site at root, as nera build passes them (dist is public/).
buildSite(root) → Promise<{ warnings: string[], logs: string[] }>
Builds the site with core's real run(), from inside root the way nera build runs it (plugins read their config relative to process.cwd()). console.log and console.warn are silenced and collected, each call's arguments joined with a space; console.error passes through. The working directory and the console are restored even when the build throws, and a test's own captureConsole is left untouched.
It changes the working directory, so it needs vitest's default forks pool; under pool: 'threads' it throws a message saying so.
useSiteCwd(files = {}) → string
For unit tests of a hook that reads config/<name>.yaml: writes files into a fresh tempDir (no defaults) and points process.cwd() at it with a vi.spyOn. The real working directory never changes. Valid for one test: call it inside the test or in beforeEach.
it('reads the output from the config', () => {
useSiteCwd({ 'config/sitemap.yaml': 'output: map.xml\n' })
expect(readConfig().output).toBe('map.xml')
})
readPublic(root, rel) → string
A built file below the site's public/. A missing file throws, listing what the build wrote, or saying the site was never built.
HTML
Core beautifies the HTML it writes, so the regular-expression readers are enough for attribute-level checks; $ and jsonLd parse.
| Export |
Returns |
pages(publicDir) |
every .html file below publicDir as { file, html }, sorted by path, file /-separated |
page(publicDir, file) |
one built page's HTML |
countTags(html, name) |
the number of opening <name> tags (<h1> and <h1 class="…">, not <h1x>) |
tags(html, name) |
each opening <name> tag's attribute string (' class="a"', '' for a bare tag) |
attr(attrs, name) |
one attribute's value from such a string, undefined when it is missing |
elementByClass(html, tag, className) |
the inner HTML of the first <tag> with className among its classes (nested tags of the same name included), undefined when there is none |
stripTags(html) |
the text: tags removed, whitespace collapsed to single spaces |
$(html) |
cheerio.load(html) |
jsonLd(html) |
every <script type="application/ld+json"> block, parsed, in document order; a block that is not valid JSON throws with its number and start |
Colour contrast
| Export |
Returns |
luminance(hex) |
the WCAG 2.2 relative luminance of a #rrggbb colour (either case), 0 to 1 |
contrast(a, b) |
the contrast ratio of two #rrggbb colours, in either order, 1 to 21 (text needs 4.5, large text 3) |
Short forms (#fff) and colour names throw; write them out. The sRGB threshold is the current 0.04045; the older 0.03928 gives the same result for every 8-bit colour.
The CLI
These need @nera-static/nera.
nera(cwd, args, { root = cwd } = {}) → Promise<{ code, stdout, stderr }>
Runs the installed nera CLI with args (['build', '--check']) in the existing absolute directory cwd, without colours (NO_COLOR=1, FORCE_COLOR=0). It never rejects on a non-zero exit: the exit code is part of the result. The CLI is the one installed for root, found from there upwards as Node resolves a package; pass your repo root when cwd has no node_modules of its own.
scaffoldStarter(repoRoot, name, args = []) → Promise<string>
For a starter repo: runs nera new <name> --starter <repoRoot> --yes --no-install ...args (offline) in a fresh tempDir and links repoRoot/node_modules into the new site, so it builds with the CLI, theme and plugins the repo installed. Returns the site root. A failing nera new throws with both output streams. From a globalSetup, remove path.dirname(site) in the teardown.
const site = await scaffoldStarter(ROOT, 'bakery', ['--name', 'Brot & Zeit', '--lang', 'de'])
expectCleanBuild(site, options = {}) → Promise<void>
Asserts that the site builds, checks and validates clean: nera build --check and nera validate exit 0 and print "No problems found", their --json forms report { ok: true, results: [] }, and neither stdout nor stderr holds a warning, a deprecation, an error mark (⚠, ❌) or "Views folder not found". Each failure names the command, the site and its full output. options ({ root }) goes to nera().
STRICT_VALIDATE
A config/validate.yaml that sets every output rule to error and names the English imprint (/imprint.html) and privacy (/privacy.html) pages. Write it into a site before expectCleanBuild(site) to prove the site stays clean under the strictest settings:
fs.writeFileSync(path.join(site, 'config/validate.yaml'), STRICT_VALIDATE)
await expectCleanBuild(site)
📦 publishTemplateSuite
For a plugin that ships templates and an npm run publish-template script. One call replaces the whole test/publish-template.test.js:
// test/publish-template.test.js
import path from 'node:path'
import { publishTemplateSuite } from '@nera-static/test-utils'
publishTemplateSuite({
root: path.resolve(import.meta.dirname, '..'),
pluginName: 'plugin-search',
templates: ['search.pug'],
assets: [{ from: 'views/search.js', to: 'js/search.js' }],
})