Skip to content

Commit

Permalink
test: improve e2e tests
Browse files Browse the repository at this point in the history
Signed-off-by: Andres Correa Casablanca <andreu@kindspells.dev>
  • Loading branch information
castarco committed Mar 15, 2024
1 parent 3932a5c commit c907ca3
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 22 deletions.
79 changes: 73 additions & 6 deletions e2e/e2e.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,13 @@ const execFile = promisify(_execFile)
const currentDir = dirname(fileURLToPath(import.meta.url))
const fixturesDir = resolve(currentDir, 'fixtures')

const _checkHtmlIsPatched = (content: string) => {
const _checkHtmlIsPatched = (
content: string,
extResources: Record<string, string> = {},
) => {
const integrityRegex =
/\s+integrity\s*=\s*("(?<integrity1>.*?)"|'(?<integrity2>.*?)')/i
const srcRegex = /\s+src\s*=\s*("(?<src1>.*?)"|'(?<src2>.*?)')/i
const scriptRegex =
/<script(?<attrs>(\s+[a-z][a-z0-9\-_]*(=('[^']*?'|"[^"]*?"))?)*?)\s*>(?<content>[\s\S]*?)<\/\s*script\s*>/gi
const styleRegex =
Expand All @@ -41,17 +45,25 @@ const _checkHtmlIsPatched = (content: string) => {
const { attrs: scriptAttrs, content: scriptContent } =
scriptMatch.groups ?? {}
assert(scriptAttrs !== undefined)
assert(scriptContent !== undefined)

const scriptIntegrityMatch = integrityRegex.exec(scriptAttrs)
assert(scriptIntegrityMatch !== null)

const scriptIntegrity =
scriptIntegrityMatch.groups?.integrity1 ??
scriptIntegrityMatch.groups?.integrity2
assert(scriptIntegrity !== undefined)

expect(scriptIntegrity).toEqual(generateSRIHash(scriptContent))
const scriptSrcMatch = srcRegex.exec(scriptAttrs)

if (scriptSrcMatch === null) {
assert(scriptContent !== undefined)
expect(scriptIntegrity).toEqual(generateSRIHash(scriptContent))
} else {
assert(!scriptContent)
const src = scriptSrcMatch.groups?.src1 ?? scriptSrcMatch.groups?.src2
assert(src !== undefined && src.length > 0)
expect(scriptIntegrity).toEqual(extResources[src])
}

// Checking for inline styles
// -------------------------------------------------------------------------
Expand Down Expand Up @@ -219,8 +231,8 @@ describe('middleware', () => {
await execFile('pnpm', ['run', 'build'], execOpts)
})

beforeEach(async (...args) => {
port = 1024 + Math.floor(Math.random() * 64511)
beforeEach(async () => {
port = 9999 + Math.floor(Math.random() * 55536)
urlBase = `http://localhost:${port}`

await cleanServer()
Expand Down Expand Up @@ -253,3 +265,58 @@ describe('middleware', () => {
await checkHtmlIsPatched('/')
})
})

describe('middleware (hybrid)', () => {
const hybridDir = resolve(fixturesDir, 'hybrid')
const execOpts = { cwd: hybridDir }

let urlBase: string
let server: PreviewServer | undefined
let port: number

beforeAll(async () => {
await execFile('pnpm', ['install'], execOpts)
await execFile('pnpm', ['run', 'clean'], execOpts)
const { stdout: buildStdout } = await execFile('pnpm', ['run', 'build'], execOpts)
expect(buildStdout).toMatch(/run the build step again/)
const { stdout: buildStdout2 } = await execFile('pnpm', ['run', 'build'], execOpts)
expect(buildStdout2).not.toMatch(/run the build step again/)
})

beforeEach(async () => {
port = 9999 + Math.floor(Math.random() * 55536)
urlBase = `http://localhost:${port}`

await cleanServer()
server = await preview({
root: hybridDir,
server: { port },
logLevel: 'debug',
})
})

const cleanServer = async () => {
if (server) {
if (!server.closed()) {
await server.stop()
}
server = undefined
}
}

afterEach(cleanServer)
afterAll(cleanServer) // Just in case

const checkHtmlIsPatched = async (
path: string,
extResources: Record<string, string> = {},
) => {
const response = await fetch(urlBase + path)
const content = await response.text()
return _checkHtmlIsPatched(content, extResources)
}

it('patches inline resources for dynamically generated pages referring static resources', async () => {
await checkHtmlIsPatched('/', { '/code.js': 'sha256-X7QGGDHgf6XMoabXvV9pW7gl3ALyZhZlgKq1s3pwmME=' })
})
})
15 changes: 4 additions & 11 deletions tests/core.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -877,7 +877,7 @@ describe('generateSRIHashesModule', () => {
const playgroundDir = resolve(testsDir, 'playground')

beforeEach(async () => {
for (const filename of await readdir(playgroundDir, { recursive: true})) {
for (const filename of await readdir(playgroundDir, { recursive: true })) {
if (filename.endsWith('.mjs')) {
await rm(resolve(playgroundDir, filename), {
force: true,
Expand All @@ -889,19 +889,12 @@ describe('generateSRIHashesModule', () => {
it('generates "empty" module when it does not exist and we pass empty hashes collection', async () => {
const modulePath = resolve(playgroundDir, 'sri.mjs')

expect(
await doesFileExist(modulePath),
).toBe(false)
expect(await doesFileExist(modulePath)).toBe(false)

const h = getEmptyHashes()
await generateSRIHashesModule(
h,
modulePath,
)
await generateSRIHashesModule(h, modulePath)

expect(
await doesFileExist(modulePath),
).toBe(true)
expect(await doesFileExist(modulePath)).toBe(true)

const hashesModule = await import(modulePath)

Expand Down
9 changes: 4 additions & 5 deletions vitest.config.e2e.mts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default defineConfig({
test: {
coverage: {
provider: 'v8',
include: ['*.mjs'],
include: ['src/*.mjs'],
exclude: [
'tests/**/*',
'e2e/**/*',
Expand All @@ -19,13 +19,12 @@ export default defineConfig({
'coverage-unit/**/*',
],
thresholds: {
statements: 25.0,
statements: 20.0,
branches: 50.0,
functions: 12.5,
lines: 25.0,
functions: 10.0,
lines: 20.0,
},
reportsDirectory: 'coverage-e2e',
reporter: [],
},
include: ['e2e/**/*.test.mts'],
},
Expand Down

0 comments on commit c907ca3

Please sign in to comment.