feat(tests): add helper to eval a module

Needed later for unit tests for code gen and runtime code
in #3605
This commit is contained in:
Tobias Bosch
2015-08-28 11:45:39 -07:00
parent 896add7d77
commit 2a126f72f3
4 changed files with 132 additions and 1 deletions

View File

@ -0,0 +1,33 @@
import {Promise, PromiseWrapper} from 'angular2/src/core/facade/async';
import {isPresent, global} from 'angular2/src/core/facade/lang';
var evalCounter = 0;
function nextModuleName() {
return `evalScript${evalCounter++}`;
}
export function evalModule(moduleSource: string, moduleImports: string[][], args: any[]):
Promise<any> {
var moduleName = nextModuleName();
var moduleSourceWithImports = [];
var importModuleNames = [];
moduleImports.forEach(sourceImport => {
var modName = sourceImport[0];
var modAlias = sourceImport[1];
importModuleNames.push(modName);
moduleSourceWithImports.push(`var ${modAlias} = require('${modName}');`);
});
moduleSourceWithImports.push(moduleSource);
var moduleBody = new Function('require', 'exports', 'module', moduleSourceWithImports.join('\n'));
var System = global['System'];
if (isPresent(System) && isPresent(System.registerDynamic)) {
System.registerDynamic(moduleName, importModuleNames, false, moduleBody);
return <Promise<any>>System.import(moduleName).then((module) => module.run(args));
} else {
var exports = {};
moduleBody(require, exports, {});
return PromiseWrapper.resolve(exports['run'](args));
}
}