Skip to content

Commit b618afd

Browse files
authored
fix(vm): bind this to module.exports (#11504)
1 parent 7396ebb commit b618afd

2 files changed

Lines changed: 32 additions & 1 deletion

File tree

‎packages/vitest/src/runtime/vm/commonjs-executor.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ export class CommonjsExecutor {
166166
const __dirname = dirname(filename)
167167
executor.requireCache.set(filename, this)
168168
try {
169-
fn(this.exports, this.require, this, filename, __dirname)
169+
fn.call(this.exports, this.exports, this.require, this, filename, __dirname)
170170
return this.exports
171171
} finally {
172172
this.loaded = true

‎test/e2e/test/vm-threads.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,37 @@ test.for(['vmThreads', 'vmForks'] as const)(
206206
},
207207
)
208208

209+
test.for(['vmThreads', 'vmForks'] as const)(
210+
'%s binds top-level this to module.exports in CommonJS',
211+
async (pool) => {
212+
const { stderr, exitCode } = await runInlineTests(
213+
{
214+
'node_modules/commonjs-this/package.json': JSON.stringify({
215+
name: 'commonjs-this',
216+
main: './index.cjs',
217+
}),
218+
'node_modules/commonjs-this/index.cjs': `
219+
'use strict'
220+
this.value = 42
221+
exports.isExports = this === module.exports
222+
`,
223+
'basic.test.js': `
224+
import { expect, test } from 'vitest'
225+
import commonjs from 'commonjs-this'
226+
227+
test('this is module.exports', () => {
228+
expect(commonjs).toEqual({ value: 42, isExports: true })
229+
})
230+
`,
231+
},
232+
{ pool },
233+
)
234+
235+
expect(stderr).toBe('')
236+
expect(exitCode).toBe(0)
237+
},
238+
)
239+
209240
// The module-sync condition was added in Node 22.12/20.19 when require(esm)
210241
// was unflagged. The fix uses the _resolveFilename conditions option which
211242
// is only available on Node 22.12+. Node 20 is unfixable and reaches EOL

0 commit comments

Comments
 (0)