-
Notifications
You must be signed in to change notification settings - Fork 53
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore: add astro testing library (#691)
- Loading branch information
Showing
3 changed files
with
56 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import { | ||
experimental_AstroContainer as AstroContainer, | ||
type ContainerRenderOptions, | ||
} from "astro/container"; | ||
import { getQueriesForElement, prettyDOM, queries } from "@testing-library/dom"; | ||
import type { BoundFunctions, prettyFormat } from "@testing-library/dom"; | ||
import { JSDOM } from "jsdom"; | ||
import type { AstroComponentFactory } from "astro/runtime/server/index.js"; | ||
export type DebugFn = ( | ||
baseElement?: HTMLElement | HTMLElement[], | ||
maxLength?: number, | ||
options?: prettyFormat.OptionsReceived, | ||
) => void; | ||
|
||
export type Result = BoundFunctions<typeof queries> & { | ||
asFragment: () => string; | ||
baseElement: HTMLElement; | ||
debug: DebugFn; | ||
}; | ||
|
||
let container: AstroContainer; | ||
|
||
export async function render( | ||
component: AstroComponentFactory, | ||
options?: Omit<ContainerRenderOptions, "routeType">, | ||
): Promise<Result> { | ||
if (!container) { | ||
container = await AstroContainer.create(); | ||
} | ||
const html = await container.renderToString(component, options); | ||
const dom = new JSDOM(html); | ||
const element = dom.window.document.body; | ||
const queryHelpers = getQueriesForElement(element); | ||
|
||
return { | ||
...queryHelpers, | ||
asFragment: () => element.innerHTML, | ||
baseElement: element, | ||
debug: (el = element, maxLength, options) => | ||
Array.isArray(el) | ||
? el.forEach((e) => console.log(prettyDOM(e, maxLength, options))) | ||
: console.log(prettyDOM(el, maxLength, options)), | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters