Skip to content

Commit

Permalink
test: refactor test utils and setup (#8135)
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed May 12, 2022
1 parent 67ff257 commit da6dc9d
Show file tree
Hide file tree
Showing 26 changed files with 274 additions and 251 deletions.
3 changes: 2 additions & 1 deletion .eslintrc.cjs
Expand Up @@ -120,7 +120,8 @@ module.exports = defineConfig({
'node/no-extraneous-import': 'off',
'node/no-extraneous-require': 'off',
'node/no-missing-import': 'off',
'node/no-missing-require': 'off'
'node/no-missing-require': 'off',
'no-undef': 'off'
}
},
{
Expand Down
34 changes: 14 additions & 20 deletions playground/cli-module/__tests__/serve.ts
Expand Up @@ -3,11 +3,18 @@

import execa from 'execa'
import kill from 'kill-port'
import { isWindows, ports, viteBinPath } from '~utils'
import {
isBuild,
isWindows,
killProcess,
ports,
rootDir,
viteBinPath
} from '~utils'

export const port = ports['cli-module']

export async function serve(root: string, isProd: boolean) {
export async function serve() {
// collect stdout and stderr streams from child processes here to avoid interfering with regular vitest output
const streams = {
build: { out: [], err: [] },
Expand Down Expand Up @@ -35,11 +42,11 @@ export async function serve(root: string, isProd: boolean) {
}

// only run `vite build` when needed
if (isProd) {
if (isBuild) {
const buildCommand = `${viteBinPath} build`
try {
const buildProcess = execa.command(buildCommand, {
cwd: root,
cwd: rootDir,
stdio: 'pipe'
})
collectStreams('build', buildProcess)
Expand All @@ -56,12 +63,12 @@ export async function serve(root: string, isProd: boolean) {

// run `vite --port x` or `vite preview --port x` to start server
const viteServerArgs = ['--port', `${port}`, '--strict-port']
if (isProd) {
if (isBuild) {
viteServerArgs.unshift('preview')
}
const serverCommand = `${viteBinPath} ${viteServerArgs.join(' ')}`
const serverProcess = execa.command(serverCommand, {
cwd: root,
cwd: rootDir,
stdio: 'pipe'
})
collectStreams('server', serverProcess)
Expand All @@ -71,7 +78,7 @@ export async function serve(root: string, isProd: boolean) {
if (serverProcess) {
const timeoutError = `server process still alive after 3s`
try {
killProcess(serverProcess)
await killProcess(serverProcess)
await resolvedOrTimeout(serverProcess, 10000, timeoutError)
} catch (e) {
if (e === timeoutError || (!serverProcess.killed && !isWindows)) {
Expand Down Expand Up @@ -132,19 +139,6 @@ async function startedOnPort(serverProcess, port, timeout) {
).finally(() => serverProcess.stdout.off('data', checkPort))
}

// helper function to kill process, uses taskkill on windows to ensure child process is killed too
function killProcess(serverProcess) {
if (isWindows) {
try {
execa.commandSync(`taskkill /pid ${serverProcess.pid} /T /F`)
} catch (e) {
console.error('failed to taskkill:', e)
}
} else {
serverProcess.kill('SIGTERM', { forceKillAfterTimeout: 2000 })
}
}

// helper function that rejects with errorMessage if promise isn't settled within ms
async function resolvedOrTimeout(promise, ms, errorMessage) {
let timer
Expand Down
34 changes: 14 additions & 20 deletions playground/cli/__tests__/serve.ts
Expand Up @@ -3,11 +3,18 @@

import execa from 'execa'
import kill from 'kill-port'
import { isWindows, ports, viteBinPath } from '~utils'
import {
isBuild,
isWindows,
killProcess,
ports,
rootDir,
viteBinPath
} from '~utils'

export const port = ports.cli

export async function serve(root: string, isProd: boolean) {
export async function serve() {
// collect stdout and stderr streams from child processes here to avoid interfering with regular vitest output
const streams = {
build: { out: [], err: [] },
Expand Down Expand Up @@ -35,11 +42,11 @@ export async function serve(root: string, isProd: boolean) {
}

// only run `vite build` when needed
if (isProd) {
if (isBuild) {
const buildCommand = `${viteBinPath} build`
try {
const buildProcess = execa.command(buildCommand, {
cwd: root,
cwd: rootDir,
stdio: 'pipe'
})
collectStreams('build', buildProcess)
Expand All @@ -56,12 +63,12 @@ export async function serve(root: string, isProd: boolean) {

// run `vite --port x` or `vite preview --port x` to start server
const viteServerArgs = ['--port', `${port}`, '--strict-port']
if (isProd) {
if (isBuild) {
viteServerArgs.unshift('preview')
}
const serverCommand = `${viteBinPath} ${viteServerArgs.join(' ')}`
const serverProcess = execa.command(serverCommand, {
cwd: root,
cwd: rootDir,
stdio: 'pipe'
})
collectStreams('server', serverProcess)
Expand All @@ -71,7 +78,7 @@ export async function serve(root: string, isProd: boolean) {
if (serverProcess) {
const timeoutError = `server process still alive after 3s`
try {
killProcess(serverProcess)
await killProcess(serverProcess)
await resolvedOrTimeout(serverProcess, 3000, timeoutError)
} catch (e) {
if (e === timeoutError || (!serverProcess.killed && !isWindows)) {
Expand Down Expand Up @@ -132,19 +139,6 @@ async function startedOnPort(serverProcess, port, timeout) {
).finally(() => serverProcess.stdout.off('data', checkPort))
}

// helper function to kill process, uses taskkill on windows to ensure child process is killed too
function killProcess(serverProcess) {
if (isWindows) {
try {
execa.commandSync(`taskkill /pid ${serverProcess.pid} /T /F`)
} catch (e) {
console.error('failed to taskkill:', e)
}
} else {
serverProcess.kill('SIGTERM', { forceKillAfterTimeout: 2000 })
}
}

// helper function that rejects with errorMessage if promise isn't settled within ms
async function resolvedOrTimeout(promise, ms, errorMessage) {
let timer
Expand Down
8 changes: 4 additions & 4 deletions playground/legacy/__tests__/ssr/serve.ts
@@ -1,14 +1,14 @@
// this is automatically detected by playground/vitestSetup.ts and will replace
// the default e2e test serve behavior
import path from 'path'
import { ports } from '~utils'
import { ports, rootDir } from '~utils'

export const port = ports['legacy/ssr']

export async function serve(root: string, _isProd: boolean) {
export async function serve() {
const { build } = await import('vite')
await build({
root,
root: rootDir,
logLevel: 'silent',
build: {
target: 'esnext',
Expand All @@ -22,7 +22,7 @@ export async function serve(root: string, _isProd: boolean) {

app.use('/', async (_req, res) => {
const { render } = await import(
path.resolve(root, './dist/server/entry-server.js')
path.resolve(rootDir, './dist/server/entry-server.js')
)
const html = await render()
res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
Expand Down
6 changes: 3 additions & 3 deletions playground/lib/__tests__/lib.spec.ts
Expand Up @@ -17,7 +17,7 @@ describe.runIf(isBuild)('build', () => {
test('umd', async () => {
expect(await page.textContent('.umd')).toBe('It works')
const code = fs.readFileSync(
path.join(testDir(), 'dist/my-lib-custom-filename.umd.js'),
path.join(testDir, 'dist/my-lib-custom-filename.umd.js'),
'utf-8'
)
// esbuild helpers are injected inside of the UMD wrapper
Expand All @@ -27,7 +27,7 @@ describe.runIf(isBuild)('build', () => {
test('iife', async () => {
expect(await page.textContent('.iife')).toBe('It works')
const code = fs.readFileSync(
path.join(testDir(), 'dist/my-lib-custom-filename.iife.js'),
path.join(testDir, 'dist/my-lib-custom-filename.iife.js'),
'utf-8'
)
// esbuild helpers are injected inside of the IIFE wrapper
Expand All @@ -40,7 +40,7 @@ describe.runIf(isBuild)('build', () => {
'hello vite'
)
const code = fs.readFileSync(
path.join(testDir(), 'dist/lib/dynamic-import-message.es.js'),
path.join(testDir, 'dist/lib/dynamic-import-message.es.js'),
'utf-8'
)
expect(code).not.toMatch('__vitePreload')
Expand Down
24 changes: 16 additions & 8 deletions playground/lib/__tests__/serve.ts
Expand Up @@ -4,19 +4,27 @@
import path from 'path'
import http from 'http'
import sirv from 'sirv'
import { page, ports, serverLogs, setViteUrl, viteTestUrl } from '~utils'
import {
isBuild,
page,
ports,
rootDir,
serverLogs,
setViteUrl,
viteTestUrl
} from '~utils'

export const port = ports.lib

export async function serve(root, isBuildTest) {
export async function serve() {
setupConsoleWarnCollector()

if (!isBuildTest) {
if (!isBuild) {
const { createServer } = await import('vite')
process.env.VITE_INLINE = 'inline-serve'
const viteServer = await (
await createServer({
root: root,
root: rootDir,
logLevel: 'silent',
server: {
watch: {
Expand All @@ -25,7 +33,7 @@ export async function serve(root, isBuildTest) {
},
host: true,
fs: {
strict: !isBuildTest
strict: !isBuild
}
},
build: {
Expand All @@ -42,19 +50,19 @@ export async function serve(root, isBuildTest) {
} else {
const { build } = await import('vite')
await build({
root,
root: rootDir,
logLevel: 'silent',
configFile: path.resolve(__dirname, '../vite.config.js')
})

await build({
root,
root: rootDir,
logLevel: 'warn', // output esbuild warns
configFile: path.resolve(__dirname, '../vite.dyimport.config.js')
})

// start static file server
const serve = sirv(path.resolve(root, 'dist'))
const serve = sirv(path.resolve(rootDir, 'dist'))
const httpServer = http.createServer((req, res) => {
if (req.url === '/ping') {
res.statusCode = 200
Expand Down
8 changes: 4 additions & 4 deletions playground/optimize-missing-deps/__test__/serve.ts
Expand Up @@ -2,13 +2,13 @@
// the default e2e test serve behavior

import path from 'path'
import { ports } from '~utils'
import { isBuild, ports, rootDir } from '~utils'

export const port = ports['optimize-missing-deps']

export async function serve(root: string, isProd: boolean) {
const { createServer } = require(path.resolve(root, 'server.js'))
const { app, vite } = await createServer(root, isProd)
export async function serve() {
const { createServer } = require(path.resolve(rootDir, 'server.js'))
const { app, vite } = await createServer(rootDir, isBuild)

return new Promise((resolve, reject) => {
try {
Expand Down
2 changes: 1 addition & 1 deletion playground/resolve-config/__tests__/resolve-config.spec.ts
Expand Up @@ -3,7 +3,7 @@ import path from 'path'
import { commandSync } from 'execa'
import { isBuild, testDir, viteBinPath } from '~utils'

const fromTestDir = (...p: string[]) => path.resolve(testDir(), ...p)
const fromTestDir = (...p: string[]) => path.resolve(testDir, ...p)

const build = (configName: string) => {
commandSync(`${viteBinPath} build`, { cwd: fromTestDir(configName) })
Expand Down
7 changes: 4 additions & 3 deletions playground/resolve-config/__tests__/serve.ts
Expand Up @@ -3,13 +3,14 @@

import path from 'path'
import fs from 'fs-extra'
import { isBuild, rootDir } from '~utils'

const configNames = ['js', 'cjs', 'mjs', 'ts']

export async function serve(root: string, isProd: boolean) {
if (!isProd) return
export async function serve() {
if (!isBuild) return

const fromTestDir = (...p: string[]) => path.resolve(root, '..', ...p)
const fromTestDir = (...p: string[]) => path.resolve(rootDir, '..', ...p)

// create separate directories for all config types:
// ./{js,cjs,mjs,ts} and ./{js,cjs,mjs,ts}-module (with package#type)
Expand Down
8 changes: 4 additions & 4 deletions playground/ssr-deps/__tests__/serve.ts
Expand Up @@ -3,15 +3,15 @@

import path from 'path'
import kill from 'kill-port'
import { ports } from '~utils'
import { isBuild, ports, rootDir } from '~utils'

export const port = ports['ssr-deps']

export async function serve(root, isProd) {
export async function serve() {
await kill(port)

const { createServer } = require(path.resolve(root, 'server.js'))
const { app, vite } = await createServer(root, isProd)
const { createServer } = require(path.resolve(rootDir, 'server.js'))
const { app, vite } = await createServer(rootDir, isBuild)

return new Promise((resolve, reject) => {
try {
Expand Down
8 changes: 4 additions & 4 deletions playground/ssr-html/__tests__/serve.ts
Expand Up @@ -3,15 +3,15 @@

import path from 'path'
import kill from 'kill-port'
import { ports } from '~utils'
import { isBuild, ports, rootDir } from '~utils'

export const port = ports['ssr-html']

export async function serve(root, isProd) {
export async function serve() {
await kill(port)

const { createServer } = require(path.resolve(root, 'server.js'))
const { app, vite } = await createServer(root, isProd)
const { createServer } = require(path.resolve(rootDir, 'server.js'))
const { app, vite } = await createServer(rootDir, isBuild)

return new Promise((resolve, reject) => {
try {
Expand Down
8 changes: 4 additions & 4 deletions playground/ssr-pug/__tests__/serve.ts
Expand Up @@ -3,15 +3,15 @@

import path from 'path'
import kill from 'kill-port'
import { ports } from '~utils'
import { isBuild, ports, rootDir } from '~utils'

export const port = ports['ssr-pug']

export async function serve(root, isProd) {
export async function serve() {
await kill(port)

const { createServer } = require(path.resolve(root, 'server.js'))
const { app, vite } = await createServer(root, isProd)
const { createServer } = require(path.resolve(rootDir, 'server.js'))
const { app, vite } = await createServer(rootDir, isBuild)

return new Promise((resolve, reject) => {
try {
Expand Down

0 comments on commit da6dc9d

Please sign in to comment.