Best JavaScript code snippet using stryker-parent
util.ts
Source:util.ts  
1import * as fs from "fs-extra";2import * as glob from "glob";3import * as path from "path";4import * as spectron from "spectron";5import {LocalRepository} from "../../electron/src/storage/types/local-repository";6import {UserRepository} from "../../electron/src/storage/types/user-repository";7import rimraf = require("rimraf");8import ITestCallbackContext = Mocha.ITestCallbackContext;9interface FnTestConfig {10    localRepository: Partial<LocalRepository>;11    platformRepositories: { [userID: string]: Partial<UserRepository> };12    overrideModules: {13        module: string,14        override: Object15    }[];16    waitForMainWindow: boolean;17    testTimeout: number;18    retries: number;19    skipFetch: boolean;20    skipUpdateCheck: boolean;21    prepareTestData: {22        name: string,23        content: string24    }[];25}26function isDevServer() {27    return ~process.argv.indexOf("--dev-server");28}29function findAppBinary() {30    if (isDevServer()) {31        return glob.sync("./node_modules/.bin/electron")[0];32    } else if (process.platform.startsWith("win")) {33        return glob.sync("./build/**/rabix-composer.exe")[0];34    } else if (process.platform.startsWith("darwin")) {35        return path.resolve("./build/mac/rabix-composer.app/Contents/MacOS/rabix-composer");36    } else {37        return path.resolve("./build/linux-unpacked/rabix-composer");38    }39}40export function getTestDir(context: ITestCallbackContext, appendPath?: string): string {41    const title          = context.test.fullTitle();42    const testRoot       = path.resolve(`${__dirname}/../../.testrun`);43    const currentTestDir = [testRoot, title, appendPath].filter(v => v).join(path.sep).replace(/\s/g, "-");44    return currentTestDir;45}46export function boot(context: ITestCallbackContext, testConfig: Partial<FnTestConfig> = {}): Promise<spectron.Application> {47    context.retries(testConfig.retries || 0);48    context.timeout(testConfig.testTimeout || 30000);49    const skipFetch       = testConfig.skipFetch !== false;50    const skipUpdateCheck = testConfig.skipUpdateCheck !== false;51    const currentTestDir = getTestDir(context);52    if (testConfig.prepareTestData) {53        testConfig.prepareTestData.forEach((data) => {54            fs.outputFileSync([currentTestDir, data.name].join(path.sep), data.content);55        });56    }57    const profilesDirPath  = currentTestDir + "/profiles";58    const localProfilePath = profilesDirPath + "/local";59    testConfig.localRepository = Object.assign(new LocalRepository(), testConfig.localRepository || {});60    testConfig.localRepository.openTabs = testConfig.localRepository.openTabs.map((tab) => {61        if (tab.id.startsWith("test:")) {62            tab.id = tab.id.replace("test:", currentTestDir);63        }64        return tab;65    });66    fs.outputFileSync(localProfilePath, JSON.stringify(testConfig.localRepository));67    if (testConfig.platformRepositories) {68        for (const userID in testConfig.platformRepositories) {69            const profilePath = profilesDirPath + `/${userID}`;70            const profileData = Object.assign(new UserRepository(), testConfig.platformRepositories[userID] || {});71            fs.outputFileSync(profilePath, JSON.stringify(profileData));72        }73    }74    const moduleOverrides = testConfig.overrideModules && JSON.stringify(testConfig.overrideModules, (key, val) => {75        if (typeof val === "function") {76            return val.toString();77        }78        return val;79    });80    const chromiumArgs = [81        isDevServer() && "./electron",82        "--spectron",83        skipFetch && "--no-fetch-on-start",84        skipUpdateCheck && "--no-update-check",85        "--user-data-dir=" + currentTestDir,86        moduleOverrides && `--override-modules=${moduleOverrides}`87    ].filter(v => v);88    const appCreation = new spectron.Application({89        path: findAppBinary(),90        args: chromiumArgs91    });92    return appCreation.start().then((app: any) => {93        Object.assign(app, {testdir: currentTestDir});94        if (testConfig.waitForMainWindow === false) {95            return app;96        }97        return app.client.waitForVisible("ct-layout").then(() => app);98    });99}100export function shutdown(app: spectron.Application) {101    if (!app) {102        return;103    }104    return app.stop().then(() => {105        return new Promise((resolve, reject) => {106            rimraf(app["testdir"], {maxBusyTries: 5}, (err) => {107                if (err) return reject(err);108                resolve();109            });110        });111    });112}113export function partialProxy(module: string, overrides: Object = {}) {114    const __module__    = module;115    const __overrides__ = JSON.stringify(overrides, (key, value) => {116        return typeof value === "function" ? value.toString() : value;117    });118    const interpolate = {119        __module__,120        __overrides__121    };122    const fn = () => {123        const module            = require("__module__");124        const overrideFunctions = __overrides__;125        const overrideKeys      = Object.keys(overrideFunctions);126        return new Proxy(module, {127            get: function (target, name: string, receiver) {128                const indexOfOverride = overrideKeys.indexOf(name);129                if (indexOfOverride === -1) {130                    return target[name];131                }132                const overrideKey = overrideKeys[indexOfOverride];133                return new Proxy(target[name], {134                    apply: function (target, context, args) {135                        return eval(`(${overrideFunctions[overrideKey]})`)(target, context, args);136                    }137                });138            }139        });140    };141    let stringified = fn.toString();142    for (const arg in interpolate) {143        stringified = stringified.replace(new RegExp(arg, "g"), interpolate[arg]);144    }145    return `(${stringified})()`;146}147export function proxerialize(fn: (...args: any[]) => any, ...inputs: any[]): any {148    const fnStr         = fn.toString();149    const argumentNames = fnStr.slice(fnStr.indexOf("(") + 1, fnStr.indexOf(")")).match(/([^\s,]+)/g) || [];150    let closureContext  = "";151    let outputStr = fn().toString();152    argumentNames.forEach((argName, index) => {153        if (argName === "$callCount") {154            closureContext += `155                module.exports.__$callCount = (module.exports.__$callCount || 0) + 1;156            `;157            outputStr = outputStr.replace(new RegExp("\\$callCount", "g"), "module.exports.__$callCount");158            return true;159        }160        const argValue = JSON.stringify(inputs[index], (key, val) => {161            switch (typeof val) {162                case "function":163                    return val.toString();164                default:165                    return val;166            }167        });168        outputStr = outputStr.replace(new RegExp(argName, "g"), argValue);169    });170    return `(function(){171        ${closureContext}172        return ${outputStr}173    })()`;...tests-migrate.js
Source:tests-migrate.js  
...12    path.resolve(`${rootPath}/${dir}/${filename}`);13const dirResolver = () => (dir, rootPath = __ROOT_PATH__) =>14    path.resolve(`${rootPath}/${dir}`);15const getResultTypes = async currentTestDir => {16    return await fs.readJSON(currentTestDir('results.json'));17};18const getEvaluationFn = async currentTestDir => {19    const evaluateBuffer = await fs.readFile(currentTestDir('evaluation.js'));20    return babel.transform(evaluateBuffer.toString(), {21        presets: ['@babel/preset-env', 'minify']22    }).code;23};24const getTestDoc = async currentTestDir => {25    const test = await fs.readJSON(currentTestDir('test.json'));26    const evaluate = test.type === 'internal'27        ? await getEvaluationFn(currentTestDir)28        : test.evaluate;29    return { ...test, evaluate };30};31const exportAction = async (testId, cmd) => {32    const configPath = cmd.config;33    if (!configPath) {34        throw new Error('No path for the configuration file provided');35    }36    const { databaseURL, serviceAccount, storageBucket } = await fs.readJSON(path.resolve(configPath));37    admin.initializeApp({38        credential: admin.credential.cert(serviceAccount),39        databaseURL,40        storageBucket41    });42    const store = admin.firestore();43    const storage = admin.storage();44    store.settings({ timestampsInSnapshots: true });45    const force = cmd.force;46    const currentTestDir = fileResolver(testId);47    try {48        const bucket = storage.bucket();49        const pictureFile = bucket.file(`testPictures/${testId}.jpg`);50        let newPictureUrl;51        const pictureExists = (await pictureFile.exists())[0];52        if (!pictureExists || force) {53            console.log('Uploading picture');54            let uuid = UUID();55            await bucket.upload(currentTestDir('picture.jpg'), {56                destination: pictureFile,57                metadata: {58                    metadata: {59                        firebaseStorageDownloadTokens: uuid60                    }61                }62            });63            newPictureUrl = `https://firebasestorage.googleapis.com/v0/b/${bucket.name}/o/${encodeURIComponent(pictureFile.name)}?alt=media&token=${uuid}`;64        }65        const doc = await getTestDoc(currentTestDir);66        if (newPictureUrl) {67            doc.pictureUrl = newPictureUrl;68        }69        const docRef = store...index.test.js
Source:index.test.js  
1import path from 'path';2import { promises as fs } from 'fs';3import nock from 'nock';4import os from 'os';5import { fileURLToPath } from 'url';6import { beforeAll } from '@jest/globals';7import load from '../index.js';8const __filename = fileURLToPath(import.meta.url);9const __dirname = path.dirname(__filename);10const fixturesDirpath = path.join(__dirname, '__fixtures__');11const readFile = (baseDir, filename, encoding = 'utf-8') => fs.readFile(path.join(baseDir, filename), encoding);12let currentTestDir;13let expectedHtml;14let srcHtml;15let srcHtml2;16let textAsset;17let imageAsset;18beforeAll(async () => {19  const promises = [20    readFile(fixturesDirpath, 'page.html'),21    readFile(fixturesDirpath, 'page2.html'),22    readFile(fixturesDirpath, 'result.html'),23    readFile(fixturesDirpath, '123.css'),24    readFile(fixturesDirpath, 'pogey.png', null),25  ];26  [srcHtml, srcHtml2, expectedHtml, textAsset, imageAsset] = await Promise.all(promises);27  nock('https://fakeaddress.com')28    .get('/')29    .reply(200, srcHtml);30  nock('https://fakeaddress.com')31    .get('/files/123.css')32    .reply(200, textAsset);33  nock('https://fakeaddress.com')34    .get('/pogey.png')35    .reply(200, imageAsset);36  nock('https://fakeaddress2.com')37    .get('/')38    .reply(200, srcHtml2);39  nock('https://fakeaddress3.com')40    .persist()41    .get('/')42    .reply(200, '');43  nock('https://unknownurl.com')44    .get('/')45    .reply(404, '');46});47beforeEach(async () => {48  currentTestDir = await fs.mkdtemp(path.join(os.tmpdir(), 'page-loader-'));49});50test('load and save a page with assets', async () => {51  await load('https://fakeaddress.com/', currentTestDir);52  const promises = [53    readFile(currentTestDir, 'fakeaddress-com.html'),54    readFile(currentTestDir, 'fakeaddress-com_files/fakeaddress-com-files-123.css'),55    readFile(currentTestDir, 'fakeaddress-com_files/fakeaddress-com-pogey.png', null),56    fs.readdir(path.join(currentTestDir, '')),57    fs.readdir(path.join(currentTestDir, 'fakeaddress-com_files')),58  ];59  const [60    resultHtml,61    resultTextAsset,62    resultImageAsset,63    dir1Files,64    dir2Files,65  ] = await Promise.all(promises);66  expect(resultHtml).toBe(expectedHtml);67  expect(resultTextAsset).toBe(textAsset);68  expect(resultImageAsset).toEqual(imageAsset);69  expect(dir1Files).toHaveLength(2);70  expect(dir2Files).toHaveLength(2);71});72test('load and save a page without assets', async () => {73  await load('https://fakeaddress2.com/', currentTestDir);74  const resultHtml = await readFile(currentTestDir, 'fakeaddress2-com.html');75  const dirFiles = await fs.readdir(currentTestDir);76  expect(resultHtml).toBe(srcHtml2);77  expect(dirFiles).toHaveLength(1);78});79test('errors', async () => {80  expect(() => load('wrong url', currentTestDir)).toThrow('Invalid URL');81  const badPath = path.join(currentTestDir, 'unknown');82  const promise2 = load('https://fakeaddress3.com', badPath);83  await expect(promise2).rejects.toThrow('ENOENT');84  const promise3 = load('https://unknownurl.com', currentTestDir);85  await expect(promise3).rejects.toThrow('404');...Using AI Code Generation
1const currentTestDir = require('stryker-parent').currentTestDir;2const currentTestDir = require('stryker-parent').currentTestDir;3const currentTestDir = require('stryker-parent').currentTestDir;4const currentTestDir = require('stryker-parent').currentTestDir;5const currentTestDir = require('stryker-parent').currentTestDir;6const currentTestDir = require('stryker-parent').currentTestDir;7const currentTestDir = require('stryker-parent').currentTestDir;8const currentTestDir = require('stryker-parent').currentTestDir;9const currentTestDir = require('stryker-parent').currentTestDir;10const currentTestDir = require('stryker-parent').currentTestDir;11const currentTestDir = require('stryker-parent').currentTestDir;12const currentTestDir = require('stryker-parent').currentTestDir;13const currentTestDir = require('stryker-parent').currentTestDir;14const currentTestDir = require('stryker-parent').currentTestDir;15const currentTestDir = require('stryker-parent').currentTestDir;16const currentTestDir = require('stryker-parent').currentTestDir;Using AI Code Generation
1const currentTestDir = require('stryker-parent').currentTestDir;2const testDir = currentTestDir();3console.log(testDir);4const currentTestDir = require('stryker-parent').currentTestDir;5const testDir = currentTestDir();6console.log(testDir);7const currentTestDir = require('stryker-parent').currentTestDir;8const testDir = currentTestDir();9console.log(testDir);10const currentTestDir = require('stryker-parent').currentTestDir;11const testDir = currentTestDir();12console.log(testDir);13const currentTestDir = require('stryker-parent').currentTestDir;14const testDir = currentTestDir();15console.log(testDir);16const currentTestDir = require('stryker-parent').currentTestDir;17const testDir = currentTestDir();18console.log(testDir);19const currentTestDir = require('stryker-parent').currentTestDir;20const testDir = currentTestDir();21console.log(testDir);22const currentTestDir = require('stryker-parent').currentTestDir;23const testDir = currentTestDir();24console.log(testDir);25const currentTestDir = require('stryker-parent').currentTestDir;26const testDir = currentTestDir();27console.log(testDir);28const currentTestDir = require('Using AI Code Generation
1var currentTestDir = require('stryker-parent').currentTestDir;2var path = require('path');3var currentTestDir = require('stryker-parent').currentTestDir;4var path = require('path');5var currentTestDir = require('stryker-parent').currentTestDir;6var path = require('path');7var currentTestDir = require('stryker-parent').currentTestDir;8var path = require('path');9var currentTestDir = require('stryker-parent').currentTestDir;10var path = require('path');11var currentTestDir = require('stryker-parent').currentTestDir;12var path = require('path');Using AI Code Generation
1const path = require('path');2const currentTestDir = require('stryker-parent').currentTestDir;3const testDir = currentTestDir(path.resolve(__dirname, 'test.js'));4console.log(testDir);5const path = require('path');6const currentTestDir = require('stryker-parent').currentTestDir;7const testDir = currentTestDir(path.resolve(__dirname, 'test.js'));8console.log(testDir);9const path = require('path');10const currentTestDir = require('stryker-parent').currentTestDir;11const testDir = currentTestDir(path.resolve(__dirname, 'test.js'));12console.log(testDir);13const path = require('path');14const currentTestDir = require('stryker-parent').currentTestDir;15const testDir = currentTestDir(path.resolve(__dirname, 'test.js'));16console.log(testDir);17const path = require('path');18const currentTestDir = require('stryker-parent').currentTestDir;19const testDir = currentTestDir(path.resolve(__dirname, 'test.js'));20console.log(testDir);21const path = require('path');22const currentTestDir = require('stryker-parent').currentTestDir;23const testDir = currentTestDir(path.resolve(__dirname, 'test.js'));24console.log(testDir);25const path = require('path');26const currentTestDir = require('stryker-parent').currentTestDir;27const testDir = currentTestDir(path.resolve(__dirname, 'test.js'));28console.log(testDir);29const path = require('path');30const currentTestDir = require('stryker-parent').currentTestDir;31const testDir = currentTestDir(path.resolve(__dirname, 'test.js'));32console.log(testDir);Using AI Code Generation
1const currentTestDir = require('stryker-parent').currentTestDir;2const path = require('path');3const testDir = currentTestDir(__dirname);4console.log(path.join(testDir, 'test.js'));5const currentTestDir = require('stryker-parent').currentTestDir;6const path = require('path');7const testDir = currentTestDir(__dirname);8console.log(path.join(testDir, 'test.js'));9const currentTestDir = require('stryker-parent').currentTestDir;10const path = require('path');11const testDir = currentTestDir(__dirname);12console.log(path.join(testDir, 'test.js'));13const currentTestDir = require('stryker-parent').currentTestDir;14const path = require('path');15const testDir = currentTestDir(__dirname);16console.log(path.join(testDir, 'test.js'));17const currentTestDir = require('stryker-parent').currentTestDir;18const path = require('path');19const testDir = currentTestDir(__dirname);20console.log(path.join(testDir, 'test.js'));21const currentTestDir = require('stryker-parent').currentTestDirUsing AI Code Generation
1var currentTestDir = require('stryker-parent').currentTestDir;2var currentTestDir = currentTestDir();3console.log(currentTestDir);4var currentTestDir = require('stryker-parent').currentTestDir;5var currentTestDir = currentTestDir('some-folder');6console.log(currentTestDir);7var currentTestDir = require('stryker-parent').currentTestDir;8var currentTestDir = currentTestDir();9console.log(currentTestDir);10var currentTestDir = require('stryker-parent').currentTestDir;11var currentTestDir = currentTestDir('some-folder');Using AI Code Generation
1const currentTestDir = require('stryker-parent').currentTestDir;2console.log(currentTestDir());3const currentTestDir = require('stryker-parent').currentTestDir;4console.log(currentTestDir());5const currentTestDir = require('stryker-parent').currentTestDir;6console.log(currentTestDir());7const currentTestDir = require('stryker-parent').currentTestDir;8console.log(currentTestDir());9const currentTestDir = require('stryker-parent').currentTestDir;10console.log(currentTestDir());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!!
