Vm2: Mocha Tests have different behavior than normal runtime

Created on 28 Apr 2017  ·  2Comments  ·  Source: patriksimek/vm2

I have a simple test case in mocha but it gives very different results:

A. Vanilla Code runs fine!

const body: string = `
            var moment = require('moment');
            setInterval(function(){
                console.log(moment().unix());
            }, 2000)
        `
const vm = new NodeVM({
    console: 'redirect',
    require: {
           external: true,
                root: process.cwd()
            }
     })
vm.run(body)
vm.on('console.log', function(consoleMessage){
      console.log('from event', consoleMessage)
})

B. In this Mocha Script, I get a new error

describe('Vanilla Script Test', function () {
    it('should return a console log of a unix from moment', function (done) {
        const body: string = `
            var moment = require('moment');
            setInterval(function(){
                console.log(moment().unix());
            }, 2000)
        `
        const vm = new NodeVM({
            console: 'redirect',
            require: {
                external: true,
                root: process.cwd()
            }
        })
        vm.run(body)
        vm.on('console.log', function(consoleMessage){
            done()
        })
    })
})

C. The new error, that only happens in Mocha

VMError: You must specify script path to load relative modules.

stale

Most helpful comment

If you pass a filename to vm.run, like vm.run(body, 'myFile.js'), it just works.

All 2 comments

If you pass a filename to vm.run, like vm.run(body, 'myFile.js'), it just works.

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Was this page helpful?
0 / 5 - 0 ratings