Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/vitest/src/runtime/vm/commonjs-executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ export class CommonjsExecutor {
const __dirname = dirname(filename)
executor.requireCache.set(filename, this)
try {
fn(this.exports, this.require, this, filename, __dirname)
fn.call(this.exports, this.exports, this.require, this, filename, __dirname)
return this.exports
} finally {
this.loaded = true
Expand Down
31 changes: 31 additions & 0 deletions test/e2e/test/vm-threads.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,37 @@ test.for(['vmThreads', 'vmForks'] as const)(
},
)

test.for(['vmThreads', 'vmForks'] as const)(
'%s binds top-level this to module.exports in CommonJS',
async (pool) => {
const { stderr, exitCode } = await runInlineTests(
{
'node_modules/commonjs-this/package.json': JSON.stringify({
name: 'commonjs-this',
main: './index.cjs',
}),
'node_modules/commonjs-this/index.cjs': `
'use strict'
this.value = 42
exports.isExports = this === module.exports
`,
'basic.test.js': `
import { expect, test } from 'vitest'
import commonjs from 'commonjs-this'
test('this is module.exports', () => {
expect(commonjs).toEqual({ value: 42, isExports: true })
})
`,
},
{ pool },
)

expect(stderr).toBe('')
expect(exitCode).toBe(0)
},
)

// The module-sync condition was added in Node 22.12/20.19 when require(esm)
// was unflagged. The fix uses the _resolveFilename conditions option which
// is only available on Node 22.12+. Node 20 is unfixable and reaches EOL
Expand Down
Loading