patriksimek / vm2

Advanced vm/sandbox for Node.js
MIT License
3.86k stars 293 forks source link

Node's test runner not available as builtin #531

Open DaniFrancisco opened 1 year ago

DaniFrancisco commented 1 year ago

Hi there!

I'm trying to run some tests from within the VM. Thought I could use Node's Test Runner but ended up having VMError: Cannot find module 'node:test' error. I confirm I've tried to add the package as a builtin to the NodeVM configuration.

Ended up using the mock feature as alternative - seems to work fine - here's a working example:

import { NodeVM } from 'vm2';
import { mock } from 'node:test';

const vm = new NodeVM({
    require: {
        builtin: ['assert/strict'],
        mock: {
            test: { mock }
        }
    }
});

vm.run(`
    const { mock } = require('node:test');
    const assert = require('node:assert/strict');

    mock.method(console, 'log');

    console.log('Hello World');

   assert.equal(console.log.mock.calls[0].arguments[0], 'Hello World');
`);

I'm curious to know why isn't this package available as a builtin and whether you find this a good alternative.

Node version: v18.16.0

Thank you!