Best JavaScript code snippet using wpt
moduleExports.test.ts
Source:moduleExports.test.ts
...13 it('should export an exported variables', () => {14 const fileContent = `// ...15module.exports.someVariable = { total: 30,};16`;17 const requirements = getExports(fileContent);18 expect(requirements).to.deep.equal({19 global: {},20 inline: [21 {22 raw: 'module.exports.someVariable = ',23 rawFullLine:24 '\nmodule.exports.someVariable = { total: 30,};',25 property: 'someVariable',26 },27 ],28 });29 });30 it('should export multiples exported variables', () => {31 const fileContent = `32module.exports.someVariable = {33 total: 30,34};35module.exports.CONSTANT="Hello";36exports.OTHER_CONSTANT="test";37console.log("Some use of " + module.exports.someVariable.total);38`;39 const requirements = getExports(fileContent);40 expect(requirements).to.deep.equal({41 global: {},42 inline: [43 {44 raw: 'module.exports.someVariable = ',45 rawFullLine: '\nmodule.exports.someVariable = {',46 property: 'someVariable',47 },48 {49 raw: 'module.exports.CONSTANT=',50 rawFullLine: 'module.exports.CONSTANT="Hello";',51 property: 'CONSTANT',52 },53 {54 raw: 'exports.OTHER_CONSTANT=',55 rawFullLine: 'exports.OTHER_CONSTANT="test";',56 property: 'OTHER_CONSTANT',57 },58 ],59 });60 });61 });62 describe('Assignment basic object support', () => {63 it('should parse inline module.exports with Object.assign()', () => {64 const fileContent =65 '\n\n\nObject.assign(module.exports, {myFunction})\n\n\n';66 const requirements = getExports(fileContent);67 expect(requirements).to.deep.equal({68 global: {69 exportedProperties: ['myFunction'],70 raw: 'Object.assign(module.exports, {myFunction})\n',71 },72 inline: [],73 });74 });75 it('should parse multiline module.exports with Object.assign()', () => {76 const fileContent = `77Object.assign(module.exports,78 {79 myFunction80 }81);`;82 const requirements = getExports(fileContent);83 expect(requirements).to.deep.equal({84 global: {85 exportedProperties: ['myFunction'],86 raw:87 'Object.assign(module.exports,\n {\n myFunction\n }\n);',88 },89 inline: [],90 });91 });92 it('should parse multiline module.exports with _.extend()', () => {93 const fileContent = `94_.extend(exports,95 {96 myFunction97 }98);`;99 const requirements = getExports(fileContent);100 expect(requirements).to.deep.equal({101 global: {102 exportedProperties: ['myFunction'],103 raw:104 '_.extend(exports,\n {\n myFunction\n }\n);',105 },106 inline: [],107 });108 });109 it('should parse inline module.exports with a function call', () => {110 const fileContent =111 '\n\n\nObject.assign(module.exports, {myFunction})\n\n\n';112 const requirements = getExports(fileContent);113 expect(requirements).to.deep.equal({114 global: {115 exportedProperties: ['myFunction'],116 raw: 'Object.assign(module.exports, {myFunction})\n',117 },118 inline: [],119 });120 });121 it('should remove comments from inline exported values', () => {122 const fileContent = `123module.exports = {124 aaa, // to be removed125 /* comment */126 bbb: 89,127 128 /**129 * Hello130 */131 ccc,132};133`;134 const requirements = getExports(fileContent);135 expect(requirements).to.deep.equal({136 global: {137 assignments: [138 {139 key: 'bbb',140 value: '89',141 },142 ],143 exportedProperties: ['aaa', 'ccc'],144 raw:145 'module.exports = {\n aaa, // to be removed\n /* comment */\n bbb: 89,\n \n /**\n * Hello\n */\n ccc,\n};\n',146 },147 inline: [],148 });149 });150 describe("module.exports = Object.assign", () => {151 it('should catch "module.export =" in inline Object.assign', () => {152 const fileContent =153 '\nmodule.exports = Object.assign(module.exports, {myFunction})\n\n\n';154 const requirements = getExports(fileContent);155 expect(requirements).to.deep.equal({156 global: {157 exportedProperties: ['myFunction'],158 raw: 'module.exports = Object.assign(module.exports, {myFunction})\n',159 },160 inline: [],161 });162 });163 it('should catch "module.export =" in multiline Object.assign', () => {164 const fileContent =165 'module.exports= Object.assign(module.exports, {\nmyFunction\n})';166 const requirements = getExports(fileContent);167 expect(requirements).to.deep.equal({168 global: {169 exportedProperties: ['myFunction'],170 raw: 'module.exports= Object.assign(module.exports, {\nmyFunction\n})',171 },172 inline: [],173 });174 });175 });176 it('should not take experimental export if disabled and warn', () => {177 const fileContent = `178// Object.assign(module.exports, { ...lib1, ...lib2 });179// module.exports = { ...lib1, ...lib2 };180`;181 const requirements = getExports(fileContent);182 expect(requirements).to.deep.equal({183 global: {},184 inline: [],185 });186 });187 });188 describe('direct exports =', () => {189 it('should parse full module.export = { ... } with direct exports', () => {190 const fileContent = `191const { insertMethod } = require("../lib");192module.exports = {193 myFunction,194 insertMethod: insertMethod,195 SomeClass,196};197async function myFunction(req) {198 return {199 someCode: "value",200 });201}202class SomeClass = {};203`;204 const requirements = getExports(fileContent);205 expect(requirements).to.deep.equal({206 global: {207 assignments: [],208 exportedProperties: [209 'myFunction',210 'SomeClass',211 'insertMethod',212 ],213 raw:214 'module.exports = {\n myFunction,\n insertMethod: insertMethod,\n SomeClass,\n};\n',215 },216 inline: [],217 });218 });219 it('should parse full module.export = variable', () => {220 const fileContent = `221class MyError extends Error {}222module.exports = MyError;223`;224 const requirements = getExports(fileContent);225 expect(requirements).to.deep.equal({226 global: {227 directAssignment: 'MyError',228 raw: 'module.exports = MyError;\n',229 },230 inline: [],231 });232 });233 it('should parse full module.export = multiline assignment', () => {234 const fileContent = `235module.exports = function (data) {236 return u_xml2js.read(data).then(json => snTree(json.manifest));237};238`;239 const requirements = getExports(fileContent);240 expect(requirements).to.deep.equal({241 global: {242 directAssignment:243 'function (data) {\n return u_xml2js.read(data).then(json => snTree(json.manifest));\n};',244 raw:245 'module.exports = function (data) {\n return u_xml2js.read(data).then(json => snTree(json.manifest));\n};',246 },247 inline: [],248 });249 });250 it('should parse full module.export = class', () => {251 const fileContent =252 'module.exports = class AttemptException extends Error {};';253 const requirements = getExports(fileContent);254 expect(requirements).to.deep.equal({255 global: {256 directAssignment:257 'class AttemptException extends Error {};',258 raw:259 'module.exports = class AttemptException extends Error {};',260 },261 inline: [],262 });263 });264 it('should parse full module.export = arrow function', () => {265 const fileContent = `module.exports = async () => {266 // code267};`;268 const requirements = getExports(fileContent);269 expect(requirements).to.deep.equal({270 global: {271 directAssignment: 'async () => {\n // code\n};',272 raw: 'module.exports = async () => {\n // code\n};',273 },274 inline: [],275 });276 });277 it('should parse full module.export with Object.assign()', () => {278 const fileContent = `279Object.assign(module.exports, {280 myFunction,281 SomeClass,282});283`;284 const requirements = getExports(fileContent);285 expect(requirements).to.deep.equal({286 global: {287 exportedProperties: ['myFunction', 'SomeClass'],288 raw:289 'Object.assign(module.exports, {\n myFunction,\n SomeClass,\n});\n',290 },291 inline: [],292 });293 });294 });295 describe('ellipsis and object assignment', () => {296 it('should parse assigned with ... ellipsis members in Object.assign', () => {297 const fileContent = `298const lib1 = require('./lib1');299const lib2 = require('./lib2');300const someFn = require('./file');301module.exports = { ...lib1, ...lib2, someFn};302`;303 const requirements = getExports(fileContent);304 expect(requirements).to.deep.equal({305 global: {306 exportedKeySets: ['lib1', 'lib2'],307 exportedProperties: ['someFn'],308 raw: 'module.exports = { ...lib1, ...lib2, someFn};\n',309 },310 inline: [],311 });312 });313 it('should parse direct assigned objects in multiline Object.assign', () => {314 const fileContent = `315const config1 = { /* keys */ };316const config2 = { /* keys */ };317Object.assign(module.exports, 318 config1, 319config2, { lib });320function lib(){}321`;322 const requirements = getExports(fileContent);323 expect(requirements).to.deep.equal({324 global: {325 exportedKeySets: ['config1', 'config2'],326 exportedProperties: ['lib'],327 raw:328 'Object.assign(module.exports, \n config1, \nconfig2, { lib });\n',329 },330 inline: [],331 });332 });333 it('should parse direct assigned objects in multiline Object.assign after {} definition', () => {334 const fileContent = `335const config1 = { /* keys */ };336const config2 = { /* keys */ };337Object.assign(module.exports, 338 config1, { lib }, config2);339function lib(){}340`;341 const requirements = getExports(fileContent);342 expect(requirements).to.deep.equal({343 global: {344 exportedKeySets: ['config1', 'config2'],345 exportedProperties: ['lib'],346 raw:347 'Object.assign(module.exports, \n config1, { lib }, config2);\n',348 },349 inline: [],350 });351 });352 it('should parse direct assigned objects members in Object.assign with no inner object', () => {353 const fileContent = `354const config1 = { /* keys */ };355const config2 = { /* keys */ };356Object.assign(module.exports, 357config1, 358config2 );359`;360 const requirements = getExports(fileContent);361 expect(requirements).to.deep.equal({362 global: {363 exportedKeySets: ['config1', 'config2'],364 exportedProperties: [],365 raw:366 'Object.assign(module.exports, \nconfig1, \nconfig2 );\n',367 },368 inline: [],369 });370 });371 });372 describe('experimental direct exported definitions', () => {373 it('should parse inline instructions', () => {374 const fileContent = `375Object.assign(module.exports, { identifiedAuthenticator: buildIdentifiedAuthenticator() });376`;377 const requirements = getExports(fileContent, true);378 expect(requirements).to.deep.equal({379 global: {380 assignments: [381 {382 key: 'identifiedAuthenticator',383 value: 'buildIdentifiedAuthenticator()',384 },385 ],386 raw:387 'Object.assign(module.exports, { identifiedAuthenticator: buildIdentifiedAuthenticator() });\n',388 },389 inline: [],390 });391 });392 it('should parse complex inline function definitions ending by });', () => {393 const fileContent = `394Object.assign(module.exports, { buildThing: (a, b) => ({ company: a, users: { $all: [b] } }) });395`;396 const requirements = getExports(fileContent, true);397 expect(requirements).to.deep.equal({398 global: {399 assignments: [400 {401 key: 'buildThing',402 value: '(a, b) => ({ company: a, users: { $all: [b] } })',403 },404 ],405 raw:406 'Object.assign(module.exports, { buildThing: (a, b) => ({ company: a, users: { $all: [b] } }) });\n',407 },408 inline: [],409 });410 });411 it('should parse hybrid inline instructions + keys', () => {412 const fileContent = `413Object.assign(module.exports, {414 identifiedAuthenticator: someConstructor(),415 someConstant,416 ...someKeySet,417});418`;419 const requirements = getExports(fileContent, true);420 expect(requirements).to.deep.equal({421 global: {422 assignments: [423 {424 key: 'identifiedAuthenticator',425 value: 'someConstructor()',426 },427 ],428 exportedProperties: ['someConstant'],429 exportedKeySets: ['someKeySet'],430 raw:431 'Object.assign(module.exports, {\n identifiedAuthenticator: someConstructor(),\n someConstant,\n ...someKeySet,\n});\n',432 },433 inline: [],434 });435 });436 it('should parse hybrid inline instructions having an ellipsis', () => {437 const fileContent = `438Object.assign(module.exports,439 lib,440 questions, {441 name: "value",442 exportedConstant,443 } 444);445`;446 const requirements = getExports(fileContent, true);447 expect(requirements).to.deep.equal({448 global: {449 assignments: [450 {451 key: 'name',452 value: '"value"',453 },454 ],455 exportedKeySets: ['lib', 'questions'],456 exportedProperties: ['exportedConstant'],457 raw:458 'Object.assign(module.exports,\n lib,\n questions, {\n name: "value",\n exportedConstant,\n } \n);\n',459 },460 inline: [],461 });462 });463 it('should parse hybrid inline instructions + keys with inline comments', () => {464 const fileContent = `465Object.assign(module.exports, {466 identifiedAuthenticator: someConstructor(), // Some comment 467 someConstant // comment468});469`;470 const requirements = getExports(fileContent, true);471 expect(requirements).to.deep.equal({472 global: {473 assignments: [474 {475 key: 'identifiedAuthenticator',476 value: 'someConstructor()',477 },478 ],479 exportedProperties: ['someConstant'],480 raw:481 'Object.assign(module.exports, {\n identifiedAuthenticator: someConstructor(), // Some comment \n someConstant // comment\n});\n',482 },483 inline: [],484 });485 });486 it('should parse various key declaration', () => {487 const fileContent = `488Object.assign(module.exports, {489 call: someConstructor(),490 str: "hello",491 number: 42,492 myFn,493 inlineArray: ["...", "..."],494 someConstant495});496`;497 const requirements = getExports(fileContent, true);498 expect(requirements).to.deep.equal({499 global: {500 assignments: [501 { key: 'call', value: 'someConstructor()' },502 { key: 'str', value: '"hello"' },503 { key: 'number', value: '42' },504 { key: 'inlineArray', value: '["...", "..."]' },505 ],506 exportedProperties: ['myFn', 'someConstant'],507 raw:508 'Object.assign(module.exports, {\n call: someConstructor(),\n str: "hello",\n number: 42,\n myFn,\n inlineArray: ["...", "..."],\n someConstant\n});\n',509 },510 inline: [],511 });512 });513 it('should parse direct = object', () => {514 const fileContent = `515module.exports = {516 getA: async req => _db.aaa.find(await getter(req), ["name", "skills"]),517 getB: async req => _db.bbb.find(await getter(req), ["name", "skills"]),518 someMethod519};520`;521 const requirements = getExports(fileContent, true);522 expect(requirements).to.deep.equal({523 global: {524 assignments: [525 {526 key: 'getA',527 value:528 'async req => _db.aaa.find(await getter(req), ["name", "skills"])',529 },530 {531 key: 'getB',532 value:533 'async req => _db.bbb.find(await getter(req), ["name", "skills"])',534 },535 ],536 exportedProperties: ['someMethod'],537 raw:538 'module.exports = {\n getA: async req => _db.aaa.find(await getter(req), ["name", "skills"]),\n getB: async req => _db.bbb.find(await getter(req), ["name", "skills"]),\n someMethod\n};\n',539 },540 inline: [],541 });542 });543 it('should parse various key declaration with inline comments', () => {544 const fileContent = `545Object.assign(module.exports, {546 call: someConstructor(), // Comment547 str: "hello",//Comment548 number: 42, // Comment549 myFn, // Comment550 inlineArray: ["...", "..."], // Comment551 someConstant // Comment552});553`;554 const requirements = getExports(fileContent, true);555 expect(requirements).to.deep.equal({556 global: {557 assignments: [558 { key: 'call', value: 'someConstructor()' },559 { key: 'str', value: '"hello"' },560 { key: 'number', value: '42' },561 { key: 'inlineArray', value: '["...", "..."]' },562 ],563 exportedProperties: ['myFn', 'someConstant'],564 raw:565 'Object.assign(module.exports, {\n call: someConstructor(), // Comment\n str: "hello",//Comment\n number: 42, // Comment\n myFn, // Comment\n inlineArray: ["...", "..."], // Comment\n someConstant // Comment\n});\n',566 },567 inline: [],568 });569 });570 it('should parse multilines object/arrays declarations following tab size', () => {571 const fileContent = `572Object.assign(module.exports, {573 singleLine: buildFirebaseAdapter({ firebaseNative }),574 multilineFn: async function (){575 // some code,576 return {577 someKey: "value",578 global579 }580 },581}582);583`;584 const requirements = getExports(fileContent, true);585 expect(requirements).to.deep.equal({586 global: {587 assignments: [588 {589 key: 'singleLine',590 value: 'buildFirebaseAdapter({ firebaseNative })',591 },592 {593 key: 'multilineFn',594 value:595 'async function (){\n // some code,\n return {\n someKey: "value",\n global\n }\n}',596 },597 ],598 exportedProperties: [],599 raw:600 'Object.assign(module.exports, {\n singleLine: buildFirebaseAdapter({ firebaseNative }),\n\n multilineFn: async function (){\n // some code,\n return {\n someKey: "value",\n global\n }\n },\n\n}\n);\n',601 },602 inline: [],603 });604 });605 it('should parse multilines function without alias', () => {606 const fileContent = `607Object.assign(module.exports, {608 myInlineFunc () { return true },609 async myMultilineFunc(file) {610 // code611 }612});613`;614 const requirements = getExports(fileContent, true);615 expect(requirements).to.deep.equal({616 global: {617 assignments: [618 {619 key: 'myInlineFunc',620 value: 'function myInlineFunc() { return true }',621 },622 {623 key: 'myMultilineFunc',624 value:625 'async function myMultilineFunc(file) {\n // code\n}',626 },627 ],628 exportedProperties: [],629 raw:630 'Object.assign(module.exports, {\n myInlineFunc () { return true },\n async myMultilineFunc(file) {\n // code\n }\n});\n',631 },632 inline: [],633 });634 });635 it('should parse functions inline and multiline comments', () => {636 const fileContent = `637Object.assign(module.exports, { 638 // This comment is important639 async function test1 (640 ...641 },642 /**643 * This is ESDoc644 * @params {function} callback645 * @return something646 */647 send: µ.test2(async function (opts) {648 ...649 }),650 /**651 * weird indent652 */653 value: 55,654});655`;656 const requirements = getExports(fileContent, true);657 expect(requirements).to.deep.equal({658 global: {659 assignments: [660 {661 comment: '// This comment is important',662 key: 'test1',663 value: 'async function test1(\n ...\n}',664 },665 {666 comment:667 '/**\n * This is ESDoc\n * @params {function} callback\n * @return something\n */',668 key: 'send',669 value:670 'µ.test2(async function (opts) {\n ...\n})',671 },672 {673 comment: '/**\n * weird indent\n */',674 key: 'value',675 value: '55',676 },677 ],678 exportedProperties: [],679 raw:680 'Object.assign(module.exports, { \n // This comment is important\n async function test1 (\n ...\n },\n\n /**\n * This is ESDoc\n * @params {function} callback\n * @return something\n */\n send: µ.test2(async function (opts) {\n ...\n }),\n\n /**\n * weird indent\n */\n value: 55,\n});\n',681 },682 inline: [],683 });684 });685 it('should parse multiline array definition', () => {686 const fileContent = `687Object.assign(module.exports, { 688 definitions: µ.containsTester([689 "aa",690 "bb",691 ]),692 tool: function (lang) {693 return lang;694 },695});696`;697 const requirements = getExports(fileContent, true);698 expect(requirements).to.deep.equal({699 global: {700 assignments: [701 {702 key: 'definitions',703 value:704 'µ.containsTester([\n "aa",\n "bb",\n])',705 },706 {707 key: 'tool',708 value: 'function (lang) {\n return lang;\n}',709 },710 ],711 exportedProperties: [],712 raw:713 'Object.assign(module.exports, { \n definitions: µ.containsTester([\n "aa",\n "bb",\n ]),\n\n tool: function (lang) {\n return lang;\n },\n});\n',714 },715 inline: [],716 });717 });718 it('should warn when there are "this.relative" uses', () => {719 const loggerWarnSpy = sandbox.stub(console, 'warn');720 const fileContent = `721Object.assign(module.exports, {722 rand: () => return Math.random(), 723 func: function (lang) {724 return this.rand() * 10;725 },726});727`;728 const requirements = getExports(fileContent, true);729 expect(requirements).to.deep.equal({730 global: {731 assignments: [732 {733 key: 'rand',734 value: '() => return Math.random()',735 },736 {737 key: 'func',738 value:739 'function (lang) {\n return this.rand() * 10;\n}',740 },741 ],742 exportedProperties: [],743 raw:744 'Object.assign(module.exports, {\n rand: () => return Math.random(), \n func: function (lang) {\n return this.rand() * 10;\n },\n});\n',745 },746 inline: [],747 });748 expect(loggerWarnSpy).to.be.calledOnceWithExactly(749 `ð beware of "this." usage in export "func"750function (lang) {751 return this.rand() * 10;752},`,753 );754 });755 });756 describe('non-supported exports', () => {757 it('should not take advanced exports when experimental mode is disabled', () => {758 const loggerWarnSpy = sandbox.stub(console, 'warn');759 const fileContent = `760Object.assign(module.exports, {761 uExternalFields: [762 "categories",763 "description",764 ]765});766`;767 const requirements = getExports(fileContent);768 expect(requirements).to.deep.equal({769 global: {},770 inline: [],771 });772 expect(loggerWarnSpy).to.be.calledOnceWithExactly(773 `â module.exports contains direct declarations (try "experimental" mode)774 uExternalFields: [775 "categories",776 "description",777 ]778`,779 );780 });781 it('should avoid global module.exports having function declared inside', () => {782 const loggerWarnSpy = sandbox.stub(console, 'warn');783 const fileContent = `784module.exports = {785 myFunction: function(){786 // This function should be moved at root scope787 // We will let the developer handle it788 },789 SomeClass,790};791`;792 const requirements = getExports(fileContent);793 expect(requirements).to.deep.equal({794 global: {},795 inline: [],796 });797 expect(loggerWarnSpy).to.be.calledOnceWithExactly(798 `â module.exports support with declaration inside is skipped (try "experimental" mode)799module.exports = {800 myFunction: function(){801 // This function should be moved at root scope802 // We will let the developer handle it803 }`,804 );805 });806 it('should avoid global module.exports having function declared inside', () => {807 const loggerWarnSpy = sandbox.stub(console, 'warn');808 const fileContent = `809 module.exports = {810 firebaseNative: buildFirebaseNative()811 };812`;813 const requirements = getExports(fileContent);814 expect(requirements).to.deep.equal({815 global: {},816 inline: [],817 });818 expect(loggerWarnSpy).to.be.calledOnceWithExactly(819 `â module.exports contains direct declarations (try "experimental" mode)820 firebaseNative: buildFirebaseNative()821 `,822 );823 });824 });...
exports.test.ts
Source:exports.test.ts
...29 myFunction,30 MY_CONST,31};32`;33 const exports = getExports(fileContent);34 const fileUpdate = rewriteExports(fileContent, exports);35 expect(fileUpdate).to.deep.equal(`36export const MY_CONST = 42;37export class MyClass(){}38export class MyError extend Error(){}39export function myFunction(){}40export async function myAsyncFunction(){}41export const myArrowFunction = async (context) => {};42`);43 });44 it('should replace successfully exported properties with a same prefixed name', () => {45 const fileContent = `46module.exports.port_http = sessionConfig.port_http;47module.exports.port_https = sessionConfig.port_https;48`;49 const exports = getExports(fileContent);50 const requirements = getRequires(fileContent);51 let fileUpdate = rewriteImports(fileContent, requirements);52 fileUpdate = rewriteExports(fileUpdate, exports);53 expect(fileUpdate).to.deep.equal(`54export const port_http = sessionConfig.port_http;55export const port_https = sessionConfig.port_https;56`);57 });58 it('should rewrite basic exported number constant) with module.exports', () => {59 const fileContent = 'module.exports.some_variable = 56';60 const exports = getExports(fileContent);61 const fileUpdate = rewriteExports(fileContent, exports);62 expect(fileUpdate).to.deep.equal('export const some_variable = 56');63 });64 it('should rewrite basic exported number constant) with exports', () => {65 const fileContent = 'exports.some_variable = 56';66 const exports = getExports(fileContent);67 const fileUpdate = rewriteExports(fileContent, exports);68 expect(fileUpdate).to.deep.equal('export const some_variable = 56');69 });70 it('should rewrite multiline exported constant (string)', () => {71 const fileContent = `72module.exports.some_variable = 'test'73module.exports.differentQuotes = "hello";74module.exports.template = \`75 multiline76\`;77`;78 const exports = getExports(fileContent);79 const fileUpdate = rewriteExports(fileContent, exports);80 expect(fileUpdate).to.deep.equal(`81export const some_variable = 'test'82export const differentQuotes = "hello";83export const template = \`84 multiline85\`;86`);87 });88 it('should rewrite exported object', () => {89 const fileContent = `90module.exports.some_variable = [\n78];91exports.CONSTANT = {92 value: 56,93 second: 'a'94}95`;96 const exports = getExports(fileContent);97 const fileUpdate = rewriteExports(fileContent, exports);98 expect(fileUpdate).to.deep.equal(`99export const some_variable = [\n78];100export const CONSTANT = {101 value: 56,102 second: 'a'103}104`);105 });106 it('should not export a named constant already defined', () => {107 const fileContent = `108function(){109 const router = "dont_export";110}111const router = Router();112exports.router = router;113`;114 const exports = getExports(fileContent);115 const fileUpdate = rewriteExports(fileContent, exports);116 expect(fileUpdate).to.deep.equal(`117function(){118 const router = "dont_export";119}120export const router = Router();121`);122 });123 it('should export a non initialized constant', () => {124 const fileContent = `125let router;126exports.router = router;127`;128 const exports = getExports(fileContent);129 const fileUpdate = rewriteExports(fileContent, exports);130 expect(fileUpdate).to.deep.equal(`131export let router;132`);133 });134 it('should rewrite exported constant and usages', () => {135 const fileContent = `136module.exports.CONSTANT = "...";137module.exports.myFunction = function () => {}138function(){139 // anything with module.exports.CONSTANT140 module.exports.myFunction(module.exports.CONSTANT);141}142`;143 const exports = getExports(fileContent);144 const fileUpdate = rewriteExports(fileContent, exports);145 expect(fileUpdate).to.deep.equal(`146export const CONSTANT = "...";147export function myFunction() => {}148function(){149 // anything with CONSTANT150 myFunction(CONSTANT);151}152`);153 });154 it('should rewrite exported constant in the Object.assign() ellipsis', () => {155 const fileContent = `156const config1 = { /* keys */ };157const config2 = { /* keys */ };158Object.assign(module.exports, 159config1, 160config2, { lib });161function lib(){}162`;163 const exports = getExports(fileContent);164 const fileUpdate = rewriteExports(fileContent, exports);165 expect(fileUpdate).to.deep.equal(`166export const config1 = { /* keys */ };167export const config2 = { /* keys */ };168export function lib(){}169`);170 });171 it('should not declare a constant with a redundant name', () => {172 const fileContent = `173const get = async (req) => {};174_.extend(module.exports, {175 get: get,176});177`;178 const exports = getExports(fileContent);179 const fileUpdate = rewriteExports(fileContent, exports);180 expect(fileUpdate).to.deep.equal(`181export const get = async (req) => {};182`);183 });184 });185 describe('inline exports - functions', () => {186 it('should rewrite unnamed arrow with const', () => {187 const fileContent = `188module.exports.myArrow = () => {};189`;190 const exports = getExports(fileContent);191 const fileUpdate = rewriteExports(fileContent, exports);192 expect(fileUpdate).to.deep.equal(`193export const myArrow = () => {};194`);195 });196 it('should exported named function', () => {197 const fileContent = `198module.exports.myFunction = function () => {};199`;200 const exports = getExports(fileContent);201 const fileUpdate = rewriteExports(fileContent, exports);202 expect(fileUpdate).to.deep.equal(`203export function myFunction() => {}204`);205 });206 it('should rewrite named async function', () => {207 const fileContent = `208module.exports.myAsyncFunction = async function() => {}209`;210 const exports = getExports(fileContent);211 const fileUpdate = rewriteExports(fileContent, exports);212 expect(fileUpdate).to.deep.equal(`213export async function myAsyncFunction() => {}214`);215 });216 it('should rewrite named arrow function', () => {217 const fileContent = `218exports.XXXX = async (user, clearPw) => {};219`;220 const exports = getExports(fileContent);221 const fileUpdate = rewriteExports(fileContent, exports);222 expect(fileUpdate).to.deep.equal(`223export async function XXXX(user, clearPw) {}224`);225 });226 it('should rewrite named arrow function ans drop the last ;', () => {227 const fileContent = `228exports._getLinkedGroupsAndMembers = async (groupIds) => {229 // multiline230};231const someInlineFunction() => {232};233`;234 const exports = getExports(fileContent);235 const fileUpdate = rewriteExports(fileContent, exports);236 expect(fileUpdate).to.deep.equal(`237export async function _getLinkedGroupsAndMembers(groupIds) {238 // multiline239}240const someInlineFunction() => {241};242`);243 });244 it('should use const for wrapped functions', () => {245 const fileContent = `246module.exports.isAuthorOfObjOrAdmin = µ.cm(async function (req) {});247`;248 const exports = getExports(fileContent);249 const fileUpdate = rewriteExports(fileContent, exports);250 expect(fileUpdate).to.deep.equal(`251export const isAuthorOfObjOrAdmin = µ.cm(async function (req) {});252`);253 });254 it('should use const for wrapped arrow functions', () => {255 const fileContent = `256module.exports.isAuthorOfObjOrAdmin = µ.cm((req) => {});257`;258 const exports = getExports(fileContent);259 const fileUpdate = rewriteExports(fileContent, exports);260 expect(fileUpdate).to.deep.equal(`261export const isAuthorOfObjOrAdmin = µ.cm((req) => {});262`);263 });264 });265 describe('Import / export', () => {266 it('should rewrite exported assignments on imported libs', () => {267 const fileContent = `268const { someMethod } = require("./myLib1");269const { someConstant } = require("./myLib2");270const { a, b } =require("./myLib3");271module.exports = { someMethod, someConstant, a,b};272`;273 const exports = getExports(fileContent);274 const requirements = getRequires(fileContent);275 let fileUpdate = rewriteImports(fileContent, requirements);276 fileUpdate = rewriteExports(fileUpdate, exports);277 expect(fileUpdate).to.deep.equal(`278export { someMethod } from "./myLib1";279export { someConstant } from "./myLib2";280export { a, b } from "./myLib3";281`);282 });283 it('should rewrite export assignments on multiple lines', () => {284 const fileContent = `285const _ = require("lodash");286const {287 someMethod, 288 someConstant,289 a,290} = require("./myLib1");291const $ = require("jquery");292module.exports = { someMethod, someConstant, a};293`;294 const exports = getExports(fileContent);295 const requirements = getRequires(fileContent);296 let fileUpdate = rewriteImports(fileContent, requirements);297 fileUpdate = rewriteExports(fileUpdate, exports);298 expect(fileUpdate).to.deep.equal(`299import _ from "lodash";300export {301 someMethod,302 someConstant,303 a,304} from "./myLib1";305import $ from "jquery";306`);307 });308 it('should rewrite export ellipsis of imported libs', () => {309 const fileContent = `310const lib1 = require("./lib1");311module.exports = { ...lib1};312`;313 const exports = getExports(fileContent);314 const requirements = getRequires(fileContent);315 let fileUpdate = rewriteImports(fileContent, requirements);316 fileUpdate = rewriteExports(fileUpdate, exports);317 expect(fileUpdate).to.deep.equal(`318export * from "./lib1";319`);320 });321 it('should not recreate const for a same named import', () => {322 const fileContent = `323const dbLogger = require('./logger');324Object.assign(module.exports, { dbLogger: dbLogger, });325`;326 const exports = getExports(fileContent);327 const requirements = getRequires(fileContent);328 let fileUpdate = rewriteImports(fileContent, requirements);329 fileUpdate = rewriteExports(fileUpdate, exports);330 expect(fileUpdate).to.deep.equal(`331export * as dbLogger from './logger';332`);333 });334 it('should rewrite exported objects and some other keys', () => {335 const fileContent = `336const lib = require("./lib.js");337const { jumanji } = require("./file1");338const { prop1, prop2 } = require("./file2");339Object.assign(module.exports, lib, {340 prop1,341 prop2,342 jumanji343});344`;345 const exports = getExports(fileContent);346 const requirements = getRequires(fileContent);347 let fileUpdate = rewriteImports(fileContent, requirements);348 fileUpdate = rewriteExports(fileUpdate, exports);349 expect(fileUpdate).to.deep.equal(`350export * from "./lib";351export { jumanji } from "./file1";352export { prop1, prop2 } from "./file2";353`);354 });355 it('should rewrite direct export all keys of a file', () => {356 const fileContent = `357const integrationsInterface = require("./integrationsInterface");358Object.assign(module.exports, integrationsInterface);359`;360 const exports = getExports(fileContent);361 const requirements = getRequires(fileContent);362 let fileUpdate = rewriteImports(fileContent, requirements);363 fileUpdate = rewriteExports(fileUpdate, exports);364 expect(fileUpdate).to.deep.equal(`365export * from "./integrationsInterface";366`);367 });368 it('should export imported property assigned to a constant and warn', () => {369 const loggerWarnSpy = sandbox.stub(console, 'warn');370 const fileContent = `371const { assertTrue } = require("./assertTrue");372const lib = require("./lib");373module.exports.assertFalse = !assertTrue;374module.exports.assertTrue = assertTrue;375`;376 const exports = getExports(fileContent);377 const requirements = getRequires(fileContent);378 let fileUpdate = rewriteImports(fileContent, requirements);379 fileUpdate = rewriteExports(fileUpdate, exports);380 expect(fileUpdate).to.deep.equal(`381import { assertTrue } from "./assertTrue";382import * as lib from "./lib";383export { assertTrue } from "./assertTrue";384export const assertFalse = !assertTrue;385`);386 expect(loggerWarnSpy).to.be.calledOnceWithExactly(387 `ð ï¸a property is used and exported, you should manually check388export { assertTrue } from "./assertTrue";`,389 );390 });391 });392 describe('default export', () => {393 it('should rewrite export direct assignment on a detached single function', () => {394 const fileContent = `395function myMethod () {}396module.exports = myMethod;397`;398 const exports = getExports(fileContent);399 const fileUpdate = rewriteExports(fileContent, exports);400 expect(fileUpdate).to.deep.equal(`401export default function myMethod () {}402`);403 });404 it('should rewrite export direct assignment on a full function definition', () => {405 const fileContent = `406module.exports = async () => {407 const sessions = await _db.programSessions.find({ sharingInfo: $ex });408});409`;410 const exports = getExports(fileContent);411 const fileUpdate = rewriteExports(fileContent, exports);412 expect(fileUpdate).to.deep.equal(`413export default async () => {414 const sessions = await _db.programSessions.find({ sharingInfo: $ex });415});416`);417 });418 it('should rewrite export direct assignment on a single line definition', () => {419 const fileContent =420 'module.exports = class AttemptException extends Error {};';421 const exports = getExports(fileContent);422 const fileUpdate = rewriteExports(fileContent, exports);423 expect(fileUpdate).to.deep.equal(424 'export default class AttemptException extends Error {};',425 );426 });427 it('should rewrite direct multiline export', () => {428 const fileContent = `429module.exports = function (data) {430 return u_xml2js.read(data).then(json => snTree(json.manifest));431};432`;433 const exports = getExports(fileContent);434 const fileUpdate = rewriteExports(fileContent, exports);435 expect(fileUpdate).to.deep.equal(`436export default function (data) {437 return u_xml2js.read(data).then(json => snTree(json.manifest));438};439`);440 });441 });442 describe('multiline exports', () => {443 it('should rewrite direct function call', () => {444 const fileContent = `Object.assign(module.exports, { identifiedAuthenticator: buildIdentifiedAuthenticator() });`;445 const exports = getExports(fileContent, true);446 const fileUpdate = rewriteExports(fileContent, exports);447 expect(fileUpdate).to.deep.equal(448 `export const identifiedAuthenticator = buildIdentifiedAuthenticator();\n`,449 );450 });451 it('should replace module.exports.variable usage', () => {452 const loggerWarnSpy = sandbox.stub(console, 'warn');453 const fileContent = `454const value = 45;455log(module.exports.value)456Object.assign(module.exports, { value });`;457 const exports = getExports(fileContent, true);458 const fileUpdate = rewriteExports(fileContent, exports);459 expect(fileUpdate).to.deep.equal(460 `461export const value = 45;462log(value)463`,464 );465 expect(loggerWarnSpy).to.not.be.called;466 });467 it('should replace module.exports.variable usage and warn if the usage is before the definition', () => {468 const loggerWarnSpy = sandbox.stub(console, 'warn');469 const fileContent = `470setTimeout(() => log(module.exports.value), 50);471const value = 45;472Object.assign(module.exports, { value });`;473 const exports = getExports(fileContent, true);474 const fileUpdate = rewriteExports(fileContent, exports);475 expect(fileUpdate).to.deep.equal(476 `477setTimeout(() => log(value), 50);478export const value = 45;479`,480 );481 expect(loggerWarnSpy).to.be.calledOnceWithExactly(482 `â ï¸an exported constant is used before its definition: "value"`,483 );484 });485 it('should export constants with an alias', () => {486 const loggerWarnSpy = sandbox.stub(console, 'warn');487 const fileContent = `488const someConstant = {};489module.exports = { 490 alias: someConstant,491};492`;493 const exports = getExports(fileContent, true);494 const fileUpdate = rewriteExports(fileContent, exports);495 expect(fileUpdate).to.deep.equal(496 `497const someConstant = {};498export const alias = someConstant;499`,500 );501 expect(loggerWarnSpy).to.not.be.called;502 });503 it('should export constants and direct exports', () => {504 const loggerWarnSpy = sandbox.stub(console, 'warn');505 const fileContent = `506import { someFn1, someFn2 } from './package'507const someConstant = 56;508Object.assign(module.exports, { 509 identifiedAuthenticator: someConstructor(),510 someConstant,511 someAlias: someConstant,512 someFn1,513 someFn2,514});515`;516 const exports = getExports(fileContent, true);517 const fileUpdate = rewriteExports(fileContent, exports);518 expect(fileUpdate).to.deep.equal(519 `520export { someFn1, someFn2 } from './package'521export const someConstant = 56;522export const identifiedAuthenticator = someConstructor();523export const someAlias = someConstant;524`,525 );526 expect(loggerWarnSpy).to.not.be.called;527 });528 it('should export constants and direct multiline exports', () => {529 const loggerWarnSpy = sandbox.stub(console, 'warn');530 const fileContent = `531import {532 someFn1,533 someFn2534} from './package'535Object.assign(module.exports, { 536 someFn1,537 someFn2,538});539`;540 const exports = getExports(fileContent, true);541 const fileUpdate = rewriteExports(fileContent, exports);542 expect(fileUpdate).to.deep.equal(543 `544export {545 someFn1,546 someFn2547} from './package'548`,549 );550 expect(loggerWarnSpy).to.not.be.called;551 });552 it('should export constants and re import used ones', () => {553 const loggerWarnSpy = sandbox.stub(console, 'warn');554 const fileContent = `555import {556 usedAndExportedMethod557} from './package';558usedAndExportedMethod();559Object.assign(module.exports, { usedAndExportedMethod });560`;561 const exports = getExports(fileContent, true);562 const fileUpdate = rewriteExports(fileContent, exports);563 expect(fileUpdate).to.deep.equal(564 `565import {566 usedAndExportedMethod567} from './package';568export {569 usedAndExportedMethod570} from './package';571usedAndExportedMethod();572`,573 );574 expect(loggerWarnSpy).to.be.calledOnceWithExactly(575 `ð ï¸a property is used and exported, you should manually check576export {577 usedAndExportedMethod578} from './package';`,579 );580 });581 it('should export declared constant', () => {582 const fileContent = `583const someMethod = async (course) => {584 const myArrow = _.every(medias, m => _canMediaBeOffline(m));585};586const myArrow = async (course) => {};587Object.assign(module.exports, { myArrow });588`;589 const exports = getExports(fileContent);590 const fileUpdate = rewriteExports(fileContent, exports);591 expect(fileUpdate).to.deep.equal(`592const someMethod = async (course) => {593 const myArrow = _.every(medias, m => _canMediaBeOffline(m));594};595export const myArrow = async (course) => {};596`);597 });598 it('should not export constant if import is not called', () => {599 const loggerWarnSpy = sandbox.stub(console, 'warn');600 const fileContent = `601import {602 usedAndExportedMethod603} from './usedAndExportedMethod'604Object.assign(module.exports, { usedAndExportedMethod });605`;606 const exports = getExports(fileContent, true);607 const fileUpdate = rewriteExports(fileContent, exports);608 expect(fileUpdate).to.deep.equal(609 `610export {611 usedAndExportedMethod612} from './usedAndExportedMethod'613`,614 );615 expect(loggerWarnSpy).to.not.be.called;616 });617 it('should warn if direct export is not found', () => {618 const loggerWarnSpy = sandbox.stub(console, 'warn');619 const fileContent = `620import { someLibs } from './package'621module.exports = { someLibs, someMissingLib };622`;623 const exports = getExports(fileContent, true);624 const fileUpdate = rewriteExports(fileContent, exports);625 expect(fileUpdate).to.deep.equal(626 `627export { someLibs } from './package'628`,629 );630 expect(loggerWarnSpy).to.be.calledOnceWithExactly(631 `ð ï¸cannot find and export declaration of property "someMissingLib"`,632 );633 });634 it('should export various direct definition', () => {635 const fileContent = `636Object.assign(module.exports, { 637 call: someConstructor(),638 str: "hello",639 number: 42,640 inlineArray: ["...", "..."],641 singleLine: buildFirebaseAdapter({ firebaseNative }),642 multilineFn: async function (){ 643 // some code,644 return {645 someKey: "value",646 global647 }648 }649});650`;651 const exports = getExports(fileContent, true);652 const fileUpdate = rewriteExports(fileContent, exports);653 expect(fileUpdate).to.deep.equal(654 `export const call = someConstructor();655export const str = "hello";656export const number = 42;657export const inlineArray = ["...", "..."];658export const singleLine = buildFirebaseAdapter({ firebaseNative });659export async function multilineFn(){660 // some code,661 return {662 someKey: "value",663 global664 }665}666`,667 );668 });669 it('should export function definition with comments', () => {670 const fileContent = `671// Inline comment method1672exports.method1 = async function () {673 // code674};675/**676 * Multiline comment 2677 */678exports.method2 = async function () {679 // code680};681`;682 const exports = getExports(fileContent, true);683 const fileUpdate = rewriteExports(fileContent, exports);684 expect(fileUpdate).to.deep.equal(685 `686// Inline comment method1687export async function method1() {688 // code689}690/**691 * Multiline comment 2692 */693export async function method2() {694 // code695}696`,697 );698 });699 it('should export and reformat named functions and arrow functions', () => {700 const fileContent = `701Object.assign(module.exports, { 702 singleLine({ param }){ /* code */ },703 async function multilineFn (){ 704 },705 async multilineFn2 (){ 706 },707 errorHandler: function (err, req, res, next) {708 // Code709 },710 multilineFn3 (){ 711 }712});713`;714 const exports = getExports(fileContent, true);715 const fileUpdate = rewriteExports(fileContent, exports);716 expect(fileUpdate).to.deep.equal(717 `export function singleLine({ param }){ /* code */ }718export async function multilineFn(){ 719}720export async function multilineFn2(){ 721}722export function errorHandler(err, req, res, next) {723 // Code724}725export function multilineFn3(){ 726}727`,728 );729 });730 it('should export reformat and replace arrow functions by functions when enable', () => {731 const fileContent = `732Object.assign(module.exports, { 733 addSeconds: (date, seconds) => {734 return date + seconds;735 },736 generateKey: async ({value} = {value: (5 + 1)}) => {737 await uuid.v4().generate();738 },739});740`;741 const exports = getExports(fileContent, true);742 const fileUpdate = rewriteExports(fileContent, exports);743 expect(fileUpdate).to.deep.equal(744 `export function addSeconds(date, seconds) {745 return date + seconds;746}747export async function generateKey({value} = {value: (5 + 1)}) {748 await uuid.v4().generate();749}750`,751 );752 });753 it('should export functions containing function callback', () => {754 const fileContent = `755Object.assign(module.exports, { 756 async function test1 (function(){ 757 // Inside callback758 }) {759 // In test1760 },761 send: µ.test2(async function (opts) {762 // Inside callback763 }),764});765`;766 const exports = getExports(fileContent, true);767 const fileUpdate = rewriteExports(fileContent, exports);768 expect(fileUpdate).to.deep.equal(769 `export async function test1(function(){ 770 // Inside callback771}) {772 // In test1773}774export const send = µ.test2(async function (opts) {775 // Inside callback776});777`,778 );779 });780 it('should rewrite functions inline and multiline comments', () => {781 const fileContent = `782Object.assign(module.exports, { 783 // This comment is important784 async function test1 (785 ...786 },787 /**788 * This is ESDoc789 * @params {function} callback790 * @return something791 */792 send: µ.test2(async function (opts) {793 ...794 }),795});796`;797 const exports = getExports(fileContent, true);798 const fileUpdate = rewriteExports(fileContent, exports);799 expect(fileUpdate).to.deep.equal(800 `// This comment is important801export async function test1(802 ...803}804/**805 * This is ESDoc806 * @params {function} callback807 * @return something808 */809export const send = µ.test2(async function (opts) {810 ...811});...
sandbox.spec.ts
Source:sandbox.spec.ts
...17 context('Compilation', () => {18 it('should compile module', async () => {19 const source = await readFixtures('simple-module.js');20 const sandbox = new Sandbox(source, 'simple-module.js');21 const module = sandbox.getExports();22 chai.expect(module).to.be.equal('Hello, world!');23 });24 it('should throw exception, if code have some inner exceptions', async () => {25 const source = await readFixtures('eval-error.js');26 const sandbox = new Sandbox(source, 'eval-error.js');27 try {28 sandbox.getExports();29 return Promise.reject('Code was compiled');30 } catch (exception) {31 }32 });33 it('should give correct filename', async () => {34 const filename = 'root/test-file.js';35 const source = await readFixtures('simple-module.js');36 const sandbox = new Sandbox(source, filename);37 chai.expect(sandbox.getFilename()).to.be.equal(filename);38 });39 it('should apply compiler to source', async () => {40 const source = await readFixtures('es6-export.js');41 const compiler = babelCompiler({42 plugins: ['@babel/plugin-transform-modules-commonjs']43 });44 const sandbox = new Sandbox(source, 'es6-export.js', {45 compiler: (code) => compiler({ source: code }, ''),46 dependencies: {}47 });48 chai.expect(sandbox.getExports().testData).to.be.equal('es6 export');49 });50 it('should give correct compiled source', async () => {51 const source = await readFixtures('simple-module.js');52 const sandbox = new Sandbox(source, 'simple-module.js');53 sandbox.getExports();54 chai.expect(sandbox.getCompiledSource()).to.be.equal(source);55 });56 it('should give correct compiled source after applying compilation pipeline', async () => {57 const compilerPostfix = '\n const value = 1';58 const source = await readFixtures('simple-module.js');59 const sandbox = new Sandbox(source, 'simple-module.js', {60 compiler: (source) => ({61 source: source + compilerPostfix62 })63 });64 sandbox.getExports();65 chai.expect(sandbox.getCompiledSource()).to.be.equal(`${source}${compilerPostfix}`);66 });67 it('should throw SyntaxError, when can\'t compile code', async () => {68 const source = await readFixtures('es6-export.js');69 const sandbox = new Sandbox(source, 'es6-export.js');70 try {71 sandbox.getExports();72 return Promise.reject('Code was compiled');73 } catch (error) {74 chai.expect(error).to.be.instanceof(SyntaxError);75 }76 });77 it('should correctly create multiple sandboxes with same source', async () => {78 const firstDep = 'test-1';79 const secondDep = 'test-2';80 const source = await readFixtures('pass-dependency.js');81 const firstSandbox = new Sandbox(source, 'pass-dependency.js', {82 dependencies: {83 insertedDependency: firstDep84 }85 });86 const secondSandbox = new Sandbox(source, 'pass-dependency.js', {87 dependencies: {88 insertedDependency: secondDep89 }90 });91 chai.expect(firstSandbox.getExports()).to.be.equal(firstDep);92 chai.expect(secondSandbox.getExports()).to.be.equal(secondDep);93 });94 it('should wrap string exception into EvalError', async () => {95 const source = await readFixtures('string-exception.js');96 const sandbox = new Sandbox(source, 'string-exception.js');97 try {98 sandbox.getExports();99 return Promise.reject('Code was compiled');100 } catch (exception) {101 chai.expect(exception).to.be.instanceof(EvalError);102 }103 });104 });105 context('Environment', () => {106 it('should have all primitives provided', async () => {107 const source = await readFixtures('primitives.js');108 const sandbox = new Sandbox(source, 'primitives.js');109 sandbox.getExports(); // should not throw110 });111 it('should correctly pass "instanceof" check for all primitives', async () => {112 const source = await readFixtures('primitives.js');113 const sandbox = new Sandbox(source, 'primitives.js');114 const {115 array,116 map,117 set,118 weakMap,119 weakSet,120 promise,121 buffer122 } = sandbox.getExports();123 chai.expect(array instanceof Array).to.be.equal(true);124 chai.expect(map instanceof Map).to.be.equal(true);125 chai.expect(set instanceof Set).to.be.equal(true);126 chai.expect(weakMap instanceof WeakMap).to.be.equal(true);127 chai.expect(weakSet instanceof WeakSet).to.be.equal(true);128 chai.expect(promise instanceof Promise).to.be.equal(true);129 chai.expect(buffer instanceof Buffer).to.be.equal(true);130 });131 it('should set global variables into own context', async () => {132 const source = await readFixtures('global-variable.js');133 const sandbox = new Sandbox(source, 'global-variable.js');134 const module = sandbox.getExports();135 const context = sandbox.getContext();136 chai.expect(module).to.be.equal(true);137 chai.expect(context['amaGlobal']).to.be.equal(true);138 chai.expect(global['amaGlobal']).to.be.equal(void 0);139 });140 it('should correctly handle function declarations', async () => {141 const source = await readFixtures('function-declaration.js');142 const sandbox = new Sandbox(source, 'function-declaration.js');143 sandbox.getExports();144 chai.expect(sandbox.getExports()).to.be.equal(1);145 });146 it('should read global variables from current process context', () => {147 const key = '__$sandbox_test_dependency$__';148 const sandbox = new Sandbox(createExportFromGlobal(key), 'global.js');149 global[key] = {};150 sandbox.getExports();151 const context = sandbox.getContext();152 chai.expect(context[key]).to.be.equal(global[key]);153 delete global[key];154 });155 });156 context('Resolve', () => {157 it('should import from "node_modules"', async () => {158 const source = await readFixtures('external-dependency.js');159 const sandbox = new Sandbox(source, 'external-dependency.js');160 chai.expect(sandbox.getExports()).to.be.equal(true);161 });162 it('should import native module', async () => {163 const source = await readFixtures('native-dependency.js');164 const sandbox = new Sandbox(source, 'native-dependency.js');165 chai.expect(sandbox.getExports()).to.be.equal(true);166 });167 it('should throw ReferenceError, when can\'t resolve dependency', async () => {168 const source = await readFixtures('pass-dependency.js');169 const sandbox = new Sandbox(source, 'pass-dependency.js');170 try {171 sandbox.getExports();172 return Promise.reject('Code was compiled');173 } catch (error) {174 chai.expect(error).to.be.instanceof(ReferenceError);175 }176 });177 });178 context('Dependency injection', () => {179 it('should handle sandbox dependencies (as static)', async () => {180 const moduleExport = 'ama come from module!';181 const source = await readFixtures('pass-dependency.js');182 const sandbox = new Sandbox(source, 'pass-dependency.js', {183 dependencies: {184 insertedDependency: moduleExport185 }186 });187 chai.expect(sandbox.getExports()).to.be.equal(moduleExport);188 });189 it('should handle sandbox dependencies (as sandbox)', async () => {190 const moduleExport = 'ama come from module!';191 const moduleContent = createExport(moduleExport);192 const source = await readFixtures('pass-dependency.js');193 const dependencySandbox = new Sandbox(moduleContent, '');194 const sandbox = new Sandbox(source, 'pass-dependency.js', {195 dependencies: {196 insertedDependency: dependencySandbox197 }198 });199 chai.expect(sandbox.getExports()).to.be.equal(moduleExport);200 });201 it('should handle mock dependencies', async () => {202 const source = await readFixtures('pass-dependency.js');203 const pathToMock = resolveFile('mock.js');204 const mock = require(pathToMock);205 const sandbox = new Sandbox(source, path.resolve('./test/fixtures/sandbox/pass-dependency.js'), {206 mocks: {207 [path.resolve('./test/fixtures/sandbox/insertedDependency')]: pathToMock208 }209 });210 chai.expect(sandbox.getExports()).to.be.equal(mock);211 });212 it('should throw ReferenceError, if can\'t resolve mock', async () => {213 const source = await readFixtures('pass-dependency.js');214 const sandbox = new Sandbox(source, path.resolve('./test/fixtures/sandbox/pass-dependency.js'), {215 mocks: {}216 });217 try {218 sandbox.getExports();219 return Promise.reject('Code was compiled');220 } catch (exception) {221 chai.expect(exception).to.be.instanceof(ReferenceError);222 }223 });224 });225 context('Exports', () => {226 it('should correctly handle exports reference', async () => {227 const source = await readFixtures('exports-reference.js');228 const sandbox = new Sandbox(source, 'exports-reference.js');229 chai.expect(sandbox.getExports().data).to.be.equal(true);230 });231 it('should add fields to "module" object', async () => {232 const source = await readFixtures('module-mutation.js');233 const sandbox = new Sandbox(source, 'module-mutation.js');234 const module = sandbox.getExports();235 const context = sandbox.getContext();236 chai.expect(module).to.be.equal(true);237 chai.expect(context.module.customField).to.be.equal(true);238 });239 it('should correctly provide commonjs module.exports object', async () => {240 const source = await readFixtures('commonjs-module-exports.js');241 const sandbox = new Sandbox(source, 'commonjs-module-exports.js');242 chai.expect(sandbox.getExports().equals).to.be.equal(true);243 });244 it('should correctly provide commonjs exports object', async () => {245 const source = await readFixtures('commonjs-exports.js');246 const sandbox = new Sandbox(source, 'commonjs-exports.js');247 chai.expect(sandbox.getExports().equals).to.be.equal(true);248 });249 });...
Using AI Code Generation
1var wpt = require('wpt');2wpt.getExports(function(err, exports){3 if(err){4 console.log(err);5 }else{6 console.log(exports);7 }8});9### getLocations(callback)10var wpt = require('wpt');11wpt.getLocations(function(err, locations){12 if(err){13 console.log(err);14 }else{15 console.log(locations);16 }17});18### getTesters(callback)19var wpt = require('wpt');20wpt.getTesters(function(err, testers){21 if(err){22 console.log(err);23 }else{24 console.log(testers);25 }26});27### getTestStatus(testId, callback)28var wpt = require('wpt');29wpt.getTestStatus('140729_8W_1', function(err, testStatus){30 if(err){31 console.log(err);32 }else{33 console.log(testStatus);34 }35});36### getTestResults(testId, callback)37var wpt = require('wpt');38wpt.getTestResults('140729_8W_1', function(err, testResults){39 if(err){40 console.log(err);41 }else{42 console.log(testResults);43 }44});45### getTestResultsByUrl(url, callback)46var wpt = require('wpt');47 if(err){48 console.log(err);49 }else{50 console.log(testResults);51 }52});53### getTestResultsByLocation(url, location, callback)
Using AI Code Generation
1var wpt = require('wpt');2var path = require('path');3var fs = require('fs');4var wpt = new wpt.WPT();5var modulePath = path.join(__dirname, 'testModule.js');6var moduleContent = fs.readFileSync(modulePath, 'utf8');7wpt.getExports(moduleContent, function(err, exports){8 if(err){9 console.log('error: ', err);10 return;11 }12 console.log('exports: ', exports);13});
Using AI Code Generation
1var wpt = require('webpagetest');2var options = {3};4var wptClient = wpt(options);5wptClient.getTestHistory(function(err, data) {6 if (err) {7 console.log(err);8 }9 console.log(data);10});
Using AI Code Generation
1const wpt = require('webpagetest');2const wptApi = new wpt('A.6b4e6f4a1b9e6f8a6a4d4d4b1a5b5e5b');3const location = 'Dulles:Chrome';4const options = {5};6wptApi.runTest(url, options, function(err, data) {7 if (err) return console.error(err);8 console.log(data);9 wptApi.getTestResults(data.data.testId, function(err, data) {10 if (err) return console.error(err);11 console.log(data);12 wptApi.getTestStatus(data.data.testId, function(err, data) {13 if (err) return console.error(err);14 console.log(data);15 });16 });17});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!