Skip to content

Commit

Permalink
wip: add test utils to astro core
Browse files Browse the repository at this point in the history
  • Loading branch information
natemoo-re committed Aug 8, 2022
1 parent 3a7e022 commit 9450da4
Show file tree
Hide file tree
Showing 14 changed files with 111 additions and 22 deletions.
5 changes: 5 additions & 0 deletions examples/with-vitest/src/components/Greeting.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
const { enthusiasm } = Astro.props;
const punctuation = enthusiasm === 0 ? '.' : enthusiasm > 9 ? '!' : '';
---
<h1>Hello <slot>world</slot>{punctuation}</h1>
27 changes: 27 additions & 0 deletions examples/with-vitest/src/components/Greeting.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { expect, test } from 'vitest'
import { render } from 'astro/test'
import Greeting from './Greeting.astro'

test('Greeting', async () => {
const { container } = await render(<Greeting />)
expect(container).toBeDefined()
expect(container.textContent).toBe('Hello world')
})

test('Greeting with name', async () => {
const { container } = await render(<Greeting>Test</Greeting>)
expect(container).toBeDefined()
expect(container.textContent).toBe('Hello Test')
})

test('Greeting unenthusiastic', async () => {
const { container } = await render(<Greeting enthusiasm={0} />)
expect(container).toBeDefined()
expect(container.textContent).toBe('Hello world.')
})

test('Greeting enthusiastic', async () => {
const { container } = await render(<Greeting enthusiasm={10} />)
expect(container).toBeDefined()
expect(container.textContent).toBe('Hello world!')
})
1 change: 1 addition & 0 deletions examples/with-vitest/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/// <reference types="astro/client" />
7 changes: 2 additions & 5 deletions examples/with-vitest/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
{
"compilerOptions": {
// Preact specific settings
"jsx": "react-jsx",
"jsxImportSource": "preact",
// Enable top-level await, and other modern ESM features.
"target": "ESNext",
"module": "ESNext",
Expand All @@ -12,7 +9,7 @@
"resolveJsonModule": true,
// Enable stricter transpilation for better output.
"isolatedModules": true,
// Add type definitions for our Astro runtime.
"types": ["astro/client"]
// Astro will directly run your TypeScript code, no transpilation needed.
"noEmit": true
}
}
3 changes: 1 addition & 2 deletions examples/with-vitest/vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { getViteConfig } from 'astro/config';

export default getViteConfig({
test: {
/* for example, use global to avoid globals imports (describe, test, expect): */
// globals: true,
setupFiles: ['./vitest.setup.ts']
},
});
1 change: 1 addition & 0 deletions examples/with-vitest/vitest.setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import 'astro/test/setup';
3 changes: 1 addition & 2 deletions packages/astro/config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@ export function defineConfig(config) {
return config;
}

export function getViteConfig(inlineConfig) {
export function getViteConfig(inlineConfig = {}) {
// Return an async Vite config getter which exposes a resolved `mode` and `command`
return async ({ mode, command }) => {
// Vite `command` is `serve | build`, but Astro uses `dev | build`
const cmd = command === 'serve' ? 'dev' : command;

// Use dynamic import to avoid pulling in deps unless used
const [
{ mergeConfig },
Expand Down
6 changes: 6 additions & 0 deletions packages/astro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
"types": "./dist/types/@types/astro.d.ts",
"typesVersions": {
"*": {
"test": [
"./test.d.ts"
],
"app": [
"./dist/types/core/app/index"
],
Expand All @@ -29,6 +32,9 @@
"./client": "./client.d.ts",
"./client-base": "./client-base.d.ts",
"./astro-jsx": "./astro-jsx.d.ts",
"./test": "./dist/core/test/index.js",
"./test.d.ts": "./test.d.ts",
"./test/setup": "./dist/core/test/setup.js",
"./jsx/*": "./dist/jsx/*",
"./jsx-runtime": "./dist/jsx-runtime/index.js",
"./config": "./config.mjs",
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/create-vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export async function createVite(
astroScriptsPlugin({ config: astroConfig }),
// The server plugin is for dev only and having it run during the build causes
// the build to run very slow as the filewatcher is triggered often.
mode !== 'build' && astroViteServerPlugin({ config: astroConfig, logging }),
mode == 'dev' && astroViteServerPlugin({ config: astroConfig, logging }),
envVitePlugin({ config: astroConfig }),
astroConfig.legacy.astroFlavoredMarkdown
? legacyMarkdownVitePlugin({ config: astroConfig, logging })
Expand Down
47 changes: 47 additions & 0 deletions packages/astro/src/core/test/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { openConfig } from "../config.js";
import { nodeLogDestination } from "../logger/node.js";
import { createResult } from '../render/result.js';
import { AstroConfig } from "../../@types/astro.js";
import { renderJSX } from "../../runtime/server/jsx.js";
import { parseHTML } from 'linkedom';

const logging = {
dest: nodeLogDestination,
level: 'error',
} as const;
let config: AstroConfig;
async function getResult() {
if (!config) {
const { astroConfig } = await openConfig({ cmd: 'dev', logging });
config = astroConfig;
}
const result = createResult({
adapterName: undefined,
origin: '',
ssr: false,
streaming: false,
logging,
markdown: config.markdown,
mode: 'development',
params: {},
pathname: '/',
props: {},
renderers: [],
async resolve(s): Promise<string> {
return s
},
site: 'http://example.com',
request: new Request('http://example.com'),
status: 200,
})
return result;
}

export async function render(vnode: any) {
const result = await getResult();
const html = await renderJSX(result, vnode);
const { document } = parseHTML(`<template id="container">${html}</template>`);

const container = document.querySelector('#container');
return { container }
}
5 changes: 5 additions & 0 deletions packages/astro/src/core/test/setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { polyfill } from "@astrojs/webapi";

polyfill(globalThis, {
exclude: 'document window'
})
22 changes: 11 additions & 11 deletions packages/astro/src/vite-plugin-astro/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,17 +178,17 @@ export function invalidateCompilation(config: AstroConfig, filename: string) {

export async function cachedCompilation(props: CompileProps): Promise<CompileResult> {
const { config, filename } = props;
let cache: CompilationCache;
if (!configCache.has(config)) {
cache = new Map();
configCache.set(config, cache);
} else {
cache = configCache.get(config)!;
}
if (cache.has(filename)) {
return cache.get(filename)!;
}
// let cache: CompilationCache;
// if (!configCache.has(config)) {
// cache = new Map();
// configCache.set(config, cache);
// } else {
// cache = configCache.get(config)!;
// }
// if (cache.has(filename)) {
// return cache.get(filename)!;
// }
const compileResult = await compile(props);
cache.set(filename, compileResult);
// cache.set(filename, compileResult);
return compileResult;
}
2 changes: 2 additions & 0 deletions packages/astro/test.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/// <reference path="./astro-jsx.d.ts" />
export function render(vnode: astroHTML.JSX.Element): Promise<{ container: HTMLTemplateElement }>;
2 changes: 1 addition & 1 deletion packages/webapi/mod.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export { pathToPosix } from './lib/utils';
export { AbortController, AbortSignal, alert, atob, Blob, btoa, ByteLengthQueuingStrategy, cancelAnimationFrame, cancelIdleCallback, CanvasRenderingContext2D, CharacterData, clearTimeout, Comment, CountQueuingStrategy, CSSStyleSheet, CustomElementRegistry, CustomEvent, Document, DocumentFragment, DOMException, Element, Event, EventTarget, fetch, File, FormData, Headers, HTMLBodyElement, HTMLCanvasElement, HTMLDivElement, HTMLDocument, HTMLElement, HTMLHeadElement, HTMLHtmlElement, HTMLImageElement, HTMLSpanElement, HTMLStyleElement, HTMLTemplateElement, HTMLUnknownElement, Image, ImageData, IntersectionObserver, MediaQueryList, MutationObserver, Node, NodeFilter, NodeIterator, OffscreenCanvas, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, Request, requestAnimationFrame, requestIdleCallback, ResizeObserver, Response, setTimeout, ShadowRoot, structuredClone, StyleSheet, Text, TransformStream, TreeWalker, URLPattern, Window, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter } from './mod.js';
export { AbortController, AbortSignal, alert, atob, Blob, btoa, ByteLengthQueuingStrategy, cancelAnimationFrame, cancelIdleCallback, CanvasRenderingContext2D, CharacterData, clearTimeout, Comment, CountQueuingStrategy, CSSStyleSheet, CustomElementRegistry, CustomEvent, Document, DocumentFragment, DOMException, Element, Event, EventTarget, fetch, File, FormData, Headers, HTMLBodyElement, HTMLCanvasElement, HTMLDivElement, HTMLDocument, HTMLElement, HTMLHeadElement, HTMLHtmlElement, HTMLImageElement, HTMLSpanElement, HTMLStyleElement, HTMLTemplateElement, HTMLUnknownElement, Image, ImageData, IntersectionObserver, MediaQueryList, MutationObserver, Node, NodeFilter, NodeIterator, OffscreenCanvas, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, Request, requestAnimationFrame, requestIdleCallback, ResizeObserver, Response, setTimeout, ShadowRoot, structuredClone, StyleSheet, Text, TransformStream, TreeWalker, URLPattern, Window, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter, } from './mod.js';
export declare const polyfill: {
(target: any, options?: PolyfillOptions): any;
internals(target: any, name: string): any;
Expand Down

0 comments on commit 9450da4

Please sign in to comment.