Skip to content

Instantly share code, notes, and snippets.

@juanpabloaj
Created March 18, 2017 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanpabloaj/212e791ec0e79d10eb8c0847eee28ae8 to your computer and use it in GitHub Desktop.
Save juanpabloaj/212e791ec0e79d10eb8c0847eee28ae8 to your computer and use it in GitHub Desktop.
var hello = function() {
return 'hello world';
};
var helloDate = function() {
console.log(new Date());
return 'hello world';
};
var returnDate = function() {
var date = new Date();
return date.toISOString();
};
var assert = require('assert');
var sinon = require('sinon');
var vm = require('vm');
var fs = require('fs');
var source = fs.readFileSync('./hello.js').toString();
var tempContext = new vm.createContext({});
var script = new vm.Script(source);
script.runInContext(tempContext);
function createFunction(moduleName, funcName, funcContent) {
return moduleName + '.' + funcName + ' = ' + funcContent;
}
var localModule = {};
for (var objName in tempContext) {
var funcName = objName;
var funcContent = tempContext[objName].toString();
var toEval = createFunction('localModule', funcName, funcContent);
eval(toEval);
}
var clock;
before(function() {
var now = new Date('2017');
clock = sinon.useFakeTimers(now.getTime());
});
it('hello', function() {
assert.strictEqual(tempContext.hello(), 'hello world');
});
it('helloDate', function () {
assert.strictEqual(localModule.helloDate(), 'hello world');
});
it('returnDate with fakeTimer', function() {
assert.strictEqual(
localModule.returnDate(), '2017-01-01T00:00:00.000Z'
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment