Skip to content

Commit

Permalink
feat!: tests now run as ESM modules
Browse files Browse the repository at this point in the history
`import.meta` is defined.

`new URL('./package.json', import.meta.url)` works now if the file is in the `--assets` folder (defaults to process.cwd())
  • Loading branch information
hugomrdias committed Apr 28, 2023
1 parent f2f5fbb commit e7bde86
Show file tree
Hide file tree
Showing 13 changed files with 140 additions and 31 deletions.
7 changes: 5 additions & 2 deletions mocks/sw/sw.config.mjs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
const path = require('path')
import path from 'path'
import { fileURLToPath } from 'url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

export default {
buildSWConfig: {
inject: [path.join(__dirname, 'sw-globals.js')],
},
afterTests: () => {
console.log('AFTER')
}
},
}
7 changes: 5 additions & 2 deletions mocks/sw/sw.function.config.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
const path = require('path')
import path from 'path'
import { fileURLToPath } from 'url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

export default function () {
return {
Expand All @@ -7,6 +10,6 @@ export default function () {
},
afterTests: () => {
console.log('AFTER')
}
},
}
}
7 changes: 5 additions & 2 deletions mocks/sw/sw.promise.config.mjs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
const path = require('path')
import path from 'path'
import { fileURLToPath } from 'url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

export default Promise.resolve({
buildSWConfig: {
inject: [path.join(__dirname, 'sw-globals.js')],
},
afterTests: () => {
console.log('AFTER')
}
},
})
6 changes: 5 additions & 1 deletion mocks/test.mocha.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable no-undef */
// eslint-disable-next-line strict
const { is } = require('uvu/assert')
const { is, ok } = require('uvu/assert')
const debug = require('debug')('app')
const { good, bad } = require('./lib')

Expand All @@ -26,5 +26,9 @@ describe('Array', () => {
it('should return "bad"', async () => {
is(await bad(), 'bad')
})

it('should has import.meta', async () => {
ok(import.meta.url)
})
})
})
37 changes: 37 additions & 0 deletions mocks/tinybench.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Bench } from 'tinybench'

const bench = new Bench({ time: 100 })

bench
.add('switch 1', () => {
let a = 1
let b = 2
const c = a
a = b
b = c
})
.add('switch 2', () => {
let a = 1
let b = 10
a = b + a
b = a - b
a = b - a
})

await bench.run()

console.table(
bench.tasks.map(({ name, result }) => ({
'Task Name': name,
'Average Time (ps)': result?.mean * 1000,
'Variance (ps)': result?.variance * 1000,
}))
)

// Output:
// ┌─────────┬────────────┬────────────────────┬────────────────────┐
// │ (index) │ Task Name │ Average Time (ps) │ Variance (ps) │
// ├─────────┼────────────┼────────────────────┼────────────────────┤
// │ 0 │ 'switch 1' │ 1.8458325710527104 │ 1.2113875253341617 │
// │ 1 │ 'switch 2' │ 1.8746935152109603 │ 1.2254725890767446 │
// └─────────┴────────────┴────────────────────┴────────────────────┘
37 changes: 37 additions & 0 deletions mocks/tinybench2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Bench } from 'tinybench'

const bench = new Bench({ time: 100 })

bench
.add('switch 1', () => {
let a = 1
let b = 2
const c = a
a = b
b = c
})
.add('switch 2', () => {
let a = 1
let b = 10
a = b + a
b = a - b
a = b - a
})

await bench.run()

console.table(
bench.tasks.map(({ name, result }) => ({
'Task Name': name,
'Average Time (ps)': result?.mean * 1000,
'Variance (ps)': result?.variance * 1000,
}))
)

// Output:
// ┌─────────┬────────────┬────────────────────┬────────────────────┐
// │ (index) │ Task Name │ Average Time (ps) │ Variance (ps) │
// ├─────────┼────────────┼────────────────────┼────────────────────┤
// │ 0 │ 'switch 1' │ 1.8458325710527104 │ 1.2113875253341617 │
// │ 1 │ 'switch 2' │ 1.8746935152109603 │ 1.2254725890767446 │
// └─────────┴────────────┴────────────────────┴────────────────────┘
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@
"lint-staged": "^13.2.2",
"mocha": "^10.2.0",
"simple-git-hooks": "^2.8.1",
"tinybench": "^2.4.0",
"typescript": "^5.0.4",
"uvu": "^0.5.6",
"zora": "^5.2.0"
Expand Down
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion src/runner-mocha.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,9 @@ class MochaRunner extends Runner {
return build(
this,
{},
`require('${require.resolve('./setup-mocha.js').replace(/\\/g, '/')}')`,
`await import('${require
.resolve('./setup-mocha.js')
.replace(/\\/g, '/')}')`,
mode
)
}
Expand Down
4 changes: 3 additions & 1 deletion src/runner-tape.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ class TapeRunner extends Runner {
plugins: [plugin],
inject: [path.join(__dirname, 'node-globals-buffer.js')],
},
`require('${require.resolve('./setup-tape.js').replace(/\\/g, '/')}')`,
`await import('${require
.resolve('./setup-tape.js')
.replace(/\\/g, '/')}')`,
mode
)
}
Expand Down
4 changes: 3 additions & 1 deletion src/runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,8 @@ export class Runner {
'Uncaught exception happened within the page. Run with --debug.'
)
})

await this.page.waitForLoadState('domcontentloaded')
return this.page
}

Expand All @@ -231,7 +233,7 @@ export class Runner {

switch (this.options.mode) {
case 'main': {
await page.addScriptTag({ url: outName })
await page.addScriptTag({ url: outName, type: 'module' })
break
}
case 'worker': {
Expand Down
20 changes: 12 additions & 8 deletions src/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ export async function getPw(browserName) {
*/
export function addWorker(filePath) {
return `
const w = new Worker("${filePath}");
const w = new Worker("${filePath}", { type: "module" });
w.onmessage = function(e) {
if(e.data.pwRunEnded) {
self.PW_TEST.end(e.data.pwRunFailed)
Expand Down Expand Up @@ -340,24 +340,26 @@ export async function build(runner, config = {}, tmpl = '', mode = 'bundle') {

// main script template
let infileContent = `
'use strict'
require('${sourceMapSupport.replace(/\\/g, '/')}').install();
import { install } from '${sourceMapSupport.replace(/\\/g, '/')}'
install()
process.env = ${JSON.stringify(runner.env)}
${tmpl}
${runner.tests.map((t) => `require('${t.replace(/\\/g, '/')}')`).join('\n')}
${runner.tests
.map((t) => `await import('${t.replace(/\\/g, '/')}')`)
.join('\n')}
`

// before script template
if (mode === 'before' && runner.options.before) {
infileContent = `
'use strict'
require('${sourceMapSupport.replace(/\\/g, '/')}').install();
import { install } from '${sourceMapSupport.replace(/\\/g, '/')}'
install()
process.env = ${JSON.stringify(runner.env)}
require('${require.resolve('../static/setup.js').replace(/\\/g, '/')}')
require('${require
await import('${require.resolve('../static/setup.js').replace(/\\/g, '/')}')
await import('${require
.resolve(path.join(runner.options.cwd, runner.options.before))
.replace(/\\/g, '/')}')
`
Expand Down Expand Up @@ -391,6 +393,8 @@ require('${require
// sourceRoot: runner.dir,
bundle: true,
sourcemap: 'inline',
platform: 'browser',
format: 'esm',
plugins: [nodePlugin, watchPlugin],
outfile: outPath,
inject: [path.join(__dirname, 'inject-process.js')],
Expand Down
30 changes: 17 additions & 13 deletions test.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import fs from 'fs'
import path from 'path'
import { ok, is } from 'uvu/assert'
import { execa } from 'execa'
import { execa, execaSync } from 'execa'

describe('mocha', function () {
it('basic', async () => {
const proc = await execa('./cli.js', ['mocks/test.mocha.js'])

is(proc.exitCode, 0, 'exit code')
ok(proc.stdout.includes('5 passing'), 'process stdout')
ok(proc.stdout.includes('6 passing'), 'process stdout')
})

it('coverage', async () => {
const proc = await execa('./cli.js', ['mocks/test.mocha.js', '--cov'])

is(proc.exitCode, 0, 'exit code')
ok(proc.stdout.includes('5 passing'), 'process stdout')
ok(proc.stdout.includes('6 passing'), 'process stdout')

const cov = JSON.parse(
// eslint-disable-next-line unicorn/prefer-json-parse-buffer
Expand All @@ -33,7 +33,7 @@ describe('mocha', function () {
])

is(proc.exitCode, 0, 'exit code')
ok(proc.stdout.includes('5 passing'), 'process stdout')
ok(proc.stdout.includes('6 passing'), 'process stdout')

const cov = JSON.parse(
// eslint-disable-next-line unicorn/prefer-json-parse-buffer
Expand All @@ -50,7 +50,7 @@ describe('mocha', function () {
])

is(proc.exitCode, 0, 'exit code')
ok(proc.stdout.includes('5 passing'), 'process stdout')
ok(proc.stdout.includes('6 passing'), 'process stdout')
})

it('coverage with cwd', async () => {
Expand All @@ -62,7 +62,7 @@ describe('mocha', function () {
])

is(proc.exitCode, 0, 'exit code')
ok(proc.stdout.includes('5 passing'), 'process stdout')
ok(proc.stdout.includes('6 passing'), 'process stdout')

const cov = JSON.parse(
// eslint-disable-next-line unicorn/prefer-json-parse-buffer
Expand All @@ -78,15 +78,15 @@ describe('mocha', function () {
})

is(proc.exitCode, 0, 'exit code')
ok(proc.stdout.includes('5 passing'), 'process stdout')
ok(proc.stdout.includes('6 passing'), 'process stdout')
ok(proc.stdout.includes('app test pass'), 'debug output')
})

it('incognito', async () => {
const proc = await execa('./cli.js', ['mocks/test.mocha.js', '--incognito'])

is(proc.exitCode, 0, 'exit code')
ok(proc.stdout.includes('5 passing'), 'process stdout')
ok(proc.stdout.includes('6 passing'), 'process stdout')
})

it('mode:worker', async () => {
Expand All @@ -97,25 +97,26 @@ describe('mocha', function () {
])

is(proc.exitCode, 0, 'exit code')
ok(proc.stdout.includes('5 passing'), 'process stdout')
ok(proc.stdout.includes('6 passing'), 'process stdout')
})

it('mocha extension', async () => {
const proc = await execa('./cli.js', ['mocks/test.mocha.js', '--extension'])
is(proc.exitCode, 0, 'exit code')
ok(proc.stdout.includes('5 passing'), 'process stdout')
ok(proc.stdout.includes('6 passing'), 'process stdout')
})

it('sw', async () => {
const proc = await execa('./cli.js', [
it('sw', () => {
const proc = execaSync('./cli.js', [
'mocks/sw/sw-test.js',
'--sw',
'mocks/sw/sw.js',
'--config',
'mocks/sw/sw.config.js',
'mocks/sw/sw.config.cjs',
])

is(proc.exitCode, 0, 'exit code')
ok(proc.stdout.includes('1 passing'), 'process stdout')
})

it('supports esm config files', async () => {
Expand All @@ -128,6 +129,7 @@ describe('mocha', function () {
])

is(proc.exitCode, 0, 'exit code')
ok(proc.stdout.includes('1 passing'), 'process stdout')
})

it('supports esm config files that return promises', async () => {
Expand All @@ -140,6 +142,7 @@ describe('mocha', function () {
])

is(proc.exitCode, 0, 'exit code')
ok(proc.stdout.includes('1 passing'), 'process stdout')
})

it('supports esm config files that return functions', async () => {
Expand All @@ -152,6 +155,7 @@ describe('mocha', function () {
])

is(proc.exitCode, 0, 'exit code')
ok(proc.stdout.includes('1 passing'), 'process stdout')
})
})

Expand Down

0 comments on commit e7bde86

Please sign in to comment.