plugin-html/test/util/test-serializer.ts

80 lines
2.6 KiB
TypeScript

import type {runBrowserTest} from "./browser-test.ts";
import type {expect} from "@jest/globals";
import chalk from "chalk";
type TestOutput = Awaited<ReturnType<typeof runBrowserTest>>;
type Serializer = Parameters<typeof expect.addSnapshotSerializer>[0];
function headerFor(name: string): string[]{
const hr = name.split('').map(()=>`#`).join('')
return [
`##${hr}##`,
`# ${name} #`,
`##${hr}##`,
];
}
export const serializer: Serializer = {
test: (val: TestOutput)=> !!(
(val?.code && Array.isArray(val?.code))
|| (val?.html && typeof(val?.html)==='string')
),
serialize(val: TestOutput,
config,
indentation,
depth,
refs,
printer): string{
const indent = (config.indent||'')+(indentation+'');
let linesOut: string[] = [];
if(val.code){
const fileLines: string[][] = val.code.slice().sort(((a,b)=>{
const sortPropsA = [!a.fileName.endsWith('html'), a.fileName];
const sortPropsB = [!b.fileName.endsWith('html'), b.fileName];
for(let i = 0; i< 2;++i){
if(sortPropsA[i]<sortPropsB[i]) return -1;
else if(sortPropsA[i]>sortPropsB[i]) return 1;
}
return 0;
})).map(({fileName, code, source})=>{
return [
...headerFor(fileName),
...((code||source).split('\n'))
]
});
linesOut = linesOut.concat(...fileLines);
}
if(val.html){
linesOut = linesOut.concat([
...headerFor("RENDERED HTML"),
...(val.html.split('\n')),
]);
}
if(val.errors?.length){
linesOut = linesOut.concat([
...headerFor("ERRORS"),
], ...val.errors.map(x=>x.split("\n")));
}
if(val.console?.length){
linesOut = linesOut.concat([
...headerFor("CONSOLE"),
], ...val.console.map(x=>x.split("\n")));
}
if(val.requestsFailed?.length){
linesOut = linesOut.concat([
...headerFor("FAILED REQUESTS"),
], ...val.requestsFailed.map(x=>x.split("\n")));
}
if(val.responses?.length){
linesOut = linesOut.concat([
...headerFor("RESPONSES"),
], ...val.responses.map(x=>x.split("\n")));
}
return linesOut.map(x=>`${indent}${x}`).join('\n');
},
}