How to use fse.readFile method in Cypress

Best JavaScript code snippet using cypress

index.test.js

Source:index.test.js Github

copy

Full Screen

...36  await Promise.all(37    files38      .filter(i => !i.includes('.cjs.'))39      .map(async i => {40        let source = await fse.readFile(i)41        let fixed = source.toString().replace(/'cjs /g, "'esm ")42        await fse.writeFile(i, fixed)43      })44  )45}46async function buildWithWebpack(path, extra = {}) {47  let bundler = webpack({48    mode: 'production',49    entry: join(path),50    output: {51      path: dirname(path)52    },53    resolve: {54      fallback: {55        path: false,56        util: false57      }58    },59    ...extra60  })61  await new Promise((resolve, reject) => {62    bundler.run((err, stats) => {63      if (err) {64        reject(err)65      } else if (stats.hasErrors()) {66        reject(stats.toJson().errors[0].message)67      } else {68        resolve()69      }70    })71  })72  return join(dirname(path), 'main.js')73}74test('compiles for Node.js', async () => {75  let [lib, runner] = await copyDirs('lib', 'runner')76  await processDir(lib)77  await replaceConsole(lib)78  await exec(`yarn add lib@${lib}`, { cwd: runner })79  let cjs = await exec('node ' + join(runner, 'index.cjs'), {80    env: { NODE_ENV: 'development' }81  })82  equal(cjs.stderr, '')83  equal(84    cjs.stdout,85    'cjs d\ncjs a\ncjs b\ncjs c\ncjs lib\ncjs f-dev\ncjs g-node-dev\n'86  )87  if (!process.version.startsWith('v10.')) {88    let esm = await exec(esmNode + join(runner, 'index.mjs'), {89      env: { NODE_ENV: 'development' }90    })91    equal(esm.stderr, '')92    equal(93      esm.stdout,94      'esm d\nesm a\nesm b\nesm c\nesm lib\nesm f-dev\nesm g-node-dev\n'95    )96  }97})98test('compiles for production Node.js', async () => {99  let [lib, runner] = await copyDirs('lib', 'runner')100  await processDir(lib)101  await replaceConsole(lib)102  await exec(`yarn add lib@${lib}`, { cwd: runner })103  let cjs = await exec('node ' + join(runner, 'index.cjs'), {104    env: { NODE_ENV: 'production' }105  })106  equal(cjs.stderr, '')107  equal(108    cjs.stdout,109    'cjs d\ncjs a\ncjs b\ncjs c\ncjs lib\ncjs f-prod\ncjs g-node-prod\n'110  )111  if (!process.version.startsWith('v10.')) {112    let esm = await exec(esmNode + join(runner, 'index.mjs'), {113      env: { NODE_ENV: 'development' }114    })115    equal(esm.stderr, '')116    equal(117      esm.stdout,118      'esm d\nesm a\nesm b\nesm c\nesm lib\nesm f-dev\nesm g-node-dev\n'119    )120  }121})122test('compiles default export for Node.js', async () => {123  let [lib, runner] = await copyDirs('default-lib', 'default-runner')124  await processDir(lib)125  await replaceConsole(lib)126  await exec(`yarn add lib@${lib}`, { cwd: runner })127  let cjs = await exec('node ' + join(runner, 'index.cjs'))128  equal(cjs.stdout, 'cjs a\ncjs lib\n')129  if (!process.version.startsWith('v10.')) {130    let esm = await exec(esmNode + join(runner, 'index.mjs'))131    equal(esm.stdout, 'esm a\nesm lib\n')132  }133})134test('allows to use sub-files for Node.js', async () => {135  let [lib, runner] = await copyDirs('lib', 'runner')136  await processDir(lib)137  await replaceConsole(lib)138  await exec(`yarn add lib@${lib}`, { cwd: runner })139  let cjs = await exec('node ' + join(runner, 'subfile.cjs'))140  equal(cjs.stdout, 'cjs a\n')141  if (!process.version.startsWith('v10.')) {142    let esm = await exec(esmNode + join(runner, 'subfile.mjs'))143    equal(esm.stdout, 'esm a\n')144  }145})146test('reads package.files', async () => {147  let [lib] = await copyDirs('files')148  await processDir(lib)149})150test('reads package.bin', async () => {151  let [lib1, lib2] = await copyDirs('bin1', 'bin2')152  await Promise.all([processDir(lib1), processDir(lib2)])153})154test('throws on non-index file', async () => {155  let [lib] = await copyDirs('non-index-error')156  let err157  try {158    await processDir(lib)159  } catch (e) {160    err = e161  }162  equal(err.message, 'Rename file.js to file/index.js')163})164test('throws on index require without .js', async () => {165  let [lib] = await copyDirs('non-js-index-error')166  let err167  try {168    await processDir(lib)169  } catch (e) {170    err = e171  }172  equal(err.message, 'Replace `index` in require() to `index.js` at index.js')173})174test('throws on un-processed require', async () => {175  let [lib] = await copyDirs('require-error')176  let err177  try {178    await processDir(lib)179  } catch (e) {180    err = e181  }182  equal(183    err.message,184    'Unsupported require() at index.js:2:2.\n' +185      'ESM supports only top-level require with static path.'186  )187})188test('throws on un-processed export', async () => {189  let [lib] = await copyDirs('named-export-error')190  let err191  try {192    await processDir(lib)193  } catch (e) {194    err = e195  }196  match(err.message, 'Unsupported export at index.js:1:1')197})198test('throws on un-processed multiline export', async () => {199  let [lib] = await copyDirs('multiline-export-error')200  let err201  try {202    await processDir(lib)203  } catch (e) {204    err = e205  }206  match(err.message, 'Unsupported export at index.js:1:1')207})208test('throws on un-processed exports', async () => {209  let [lib] = await copyDirs('export-error')210  let err211  try {212    await processDir(lib)213  } catch (e) {214    err = e215  }216  equal(217    err.message,218    'Replace module.exports.x to module.exports = { x } at index.js:1:1'219  )220})221test('compiles for TypeScript', async () => {222  let [lib, runner] = await copyDirs('lib', 'ts-runner')223  await processDir(lib)224  await replaceConsole(lib)225  await exec(`yarn add lib@${lib}`, { cwd: runner })226  await exec('npx tsc --build ' + join(runner, 'tsconfig.json'))227})228test('works with ts-node', async () => {229  let [lib, runner] = await copyDirs('lib', 'ts-node')230  await processDir(lib)231  await replaceConsole(lib)232  await exec(`yarn add lib@${lib}`, { cwd: runner })233  let { stdout } = await exec('npx ts-node ' + join(runner, 'index.ts'))234  equal(235    stdout,236    'cjs d\ncjs a\ncjs b\ncjs c\ncjs lib\ncjs f-dev\ncjs g-node-dev\n'237  )238})239test('works with modules in webpack', async () => {240  let [lib, clientLib, client] = await copyDirs('lib', 'client-lib', 'client')241  await processDir(lib)242  await processDir(clientLib)243  await replaceConsole(lib)244  await exec(`yarn add lib@${lib}`, { cwd: client })245  await exec(`yarn add client-lib@${clientLib}`, { cwd: client })246  let bundle = await buildWithWebpack(join(client, 'index.js'))247  let str = (await fse.readFile(bundle)).toString()248  not.match(str, 'shaked-export')249  not.match(str, 'cjs')250  match(str, 'esm d')251  match(str, 'esm a')252  match(str, 'esm b')253  match(str, 'esm browser c')254  match(str, 'esm lib')255  match(str, 'esm f-prod')256  match(str, 'esm g-browser-prod')257  not.match(str, 'esm f-dev')258})259test('works with modules in esbuild', async () => {260  let [lib, runner] = await copyDirs('lib', 'runner')261  await processDir(lib)262  await replaceConsole(lib)263  await exec(`yarn add lib@${lib}`, { cwd: runner })264  let bundle = join(runner, 'bundle.js')265  await exec(266    `npx esbuild --bundle ${join(runner, 'index.mjs')} ` +267      `--minify --outfile=${bundle} ` +268      `--define:process.env.NODE_ENV='"production"' ` +269      `--external:path --external:util`270  )271  let str = (await fse.readFile(bundle)).toString()272  not.match(str, 'shaked-export')273  not.match(str, 'cjs')274  match(str, 'esm d')275  match(str, 'esm a')276  match(str, 'esm b')277  match(str, 'esm browser c')278  match(str, 'esm lib')279  match(str, 'esm f-prod')280  match(str, 'esm g-browser-prod')281  not.match(str, 'esm f-dev')282})283test('works with modules in development webpack', async () => {284  let [lib, clientLib, client] = await copyDirs('lib', 'client-lib', 'client')285  await processDir(lib)286  await processDir(clientLib)287  await replaceConsole(lib)288  await exec(`yarn add lib@${lib}`, { cwd: client })289  await exec(`yarn add client-lib@${clientLib}`, { cwd: client })290  let bundle = await buildWithWebpack(join(client, 'index.js'), {291    mode: 'development'292  })293  let str = (await fse.readFile(bundle)).toString()294  match(str, 'esm f-dev')295  match(str, 'esm g-browser-dev')296  not.match(str, 'esm f-prod')297})298test('works with modules in Rollup', async () => {299  let [lib, clientLib, client] = await copyDirs('lib', 'client-lib', 'client')300  await processDir(lib)301  await processDir(clientLib)302  await replaceConsole(lib)303  await exec(`yarn add lib@${lib}`, { cwd: client })304  await exec(`yarn add client-lib@${clientLib}`, { cwd: client })305  let bundle = join(client, 'bundle.js')306  await exec(307    `npx rollup ${join(client, 'index.js')} ` +308      `-o ${bundle} -f es ` +309      '-p @rollup/plugin-node-resolve={browser:true} ' +310      '-p rollup-plugin-svg ' +311      '-p @rollup/plugin-replace=\'{"process.env.NODE_ENV":"\\"production\\""}\' ' +312      '-p rollup-plugin-terser'313  )314  let str = (await fse.readFile(bundle)).toString()315  not.match(str, 'shaked-export')316  not.match(str, 'cjs')317  match(str, 'esm d')318  match(str, 'esm a')319  match(str, 'esm b')320  match(str, 'esm browser c')321  match(str, 'esm lib')322  match(str, 'esm f-prod')323  match(str, 'esm g-browser-prod')324  not.match(str, 'esm f-dev')325})326test('works with modules in Parcel', async () => {327  let [lib, clientLib, client] = await copyDirs('lib', 'client-lib', 'client')328  await processDir(lib)329  await processDir(clientLib)330  await replaceConsole(lib)331  await exec(`yarn add lib@${lib}`, { cwd: client })332  await exec(`yarn add client-lib@${clientLib}`, { cwd: client })333  await exec(334    `npx parcel build ${join(client, 'index.js')} ` +335      `-d ${client} -o bundle.js --no-cache --experimental-scope-hoisting`,336    { env: { ...process.env, NODE_ENV: 'production' } }337  )338  let str = (await fse.readFile(join(client, 'bundle.js'))).toString()339  not.match(str, 'shaked-export')340  not.match(str, 'cjs')341  match(str, 'esm d')342  match(str, 'esm a')343  match(str, 'esm b')344  match(str, 'esm browser c')345  match(str, 'esm lib')346  match(str, 'esm f-prod')347  match(str, 'esm g-browser-prod')348  not.match(str, 'esm f-dev')349})350test('works with modules in developer Parcel', async () => {351  let [lib, clientLib, client] = await copyDirs('lib', 'client-lib', 'client')352  await processDir(lib)353  await processDir(clientLib)354  await replaceConsole(lib)355  await exec(`yarn add lib@${lib}`, { cwd: client })356  await exec(`yarn add client-lib@${clientLib}`, { cwd: client })357  await exec(358    `npx parcel build ${join(client, 'index.js')} ` +359      `-d ${client} -o bundle.js --no-cache --experimental-scope-hoisting`,360    { env: { ...process.env, NODE_ENV: 'development' } }361  )362  let str = (await fse.readFile(join(client, 'bundle.js'))).toString()363  match(str, 'esm f-dev')364  match(str, 'esm g-browser-dev')365  not.match(str, 'esm f-prod')366})367if (nodeVersion <= 16) {368  test('compiles for React Native', async () => {369    let [lib, runner] = await copyDirs('rn-lib', 'rn-runner')370    await processDir(lib)371    await replaceConsole(lib)372    await exec(`yarn add rn-lib@${lib}`, { cwd: runner })373    let config = {374      ...(await metro.loadConfig()),375      projectRoot: runner,376      watchFolders: [runner, join(testRoot, '..', 'node_modules')],377      reporter: { update: () => {} },378      cacheStores: [],379      resetCache: true,380      resolver: {381        resolverMainFields: ['react-native', 'browser', 'main']382      },383      transformer: {384        babelTransformerPath: 'metro-react-native-babel-transformer'385      }386    }387    let { code } = await metro.runBuild(config, {388      entry: 'index.js',389      minify: false,390      sourceMap: false391    })392    match(code, "console.log('native a')")393    match(code, "console.log('esm b')")394    match(code, "console.log('esm c')")395  })396}397test('copy package.json fields as a conditions for exports field', async () => {398  let [normalizeCss] = await copyDirs('normalize-css')399  await processDir(normalizeCss)400  let pkg = await fse.readFile(join(normalizeCss, 'package.json'))401  equal(JSON.parse(pkg.toString()), {402    'name': 'normalize-css',403    'style': './index.css',404    'styl': './index.css',405    'sass': './dir/index.sass',406    'less': './dir/index.less',407    'type': 'module',408    'main': 'index.cjs',409    'module': 'index.js',410    'react-native': 'index.js',411    'exports': {412      '.': {413        default: './index.js',414        require: './index.cjs',415        import: './index.js',416        style: './index.css',417        styl: './index.css',418        sass: './dir/index.sass',419        less: './dir/index.less'420      },421      './package.json': './package.json',422      './index.css': './index.css',423      './dir/index.sass': './dir/index.sass',424      './dir/index.less': './dir/index.less'425    }426  })427})428test('supports process.env.NODE_ENV', async () => {429  let [nodeEnv] = await copyDirs('node-env')430  await processDir(nodeEnv)431  await replaceConsole(nodeEnv)432  let packageJsonContent = JSON.parse(433    (await fse.readFile(join(nodeEnv, 'package.json'))).toString()434  )435  equal(packageJsonContent.exports['.'], {436    browser: {437      production: './index.prod.js',438      development: './index.dev.js',439      default: './index.prod.js'440    },441    import: './index.js',442    require: './index.cjs',443    default: './index.js'444  })445  equal(packageJsonContent.exports['./a'], {446    browser: {447      production: './a/index.prod.js',448      development: './a/index.dev.js',449      default: './a/index.prod.js'450    },451    require: './a/index.cjs',452    import: './a/index.js',453    default: './a/index.js'454  })455  let nestedPackageJsonContent = JSON.parse(456    (await fse.readFile(join(nodeEnv, 'a/package.json'))).toString()457  )458  equal(nestedPackageJsonContent, {459    'browser': {460      './index.cjs': './index.browser.cjs',461      './index.js': './index.browser.js'462    },463    'main': 'index.cjs',464    'module': 'index.js',465    'react-native': 'index.js',466    'type': 'module'467  })468  let indexDerivedProd = (469    await fse.readFile(join(nodeEnv, 'index.prod.js'))470  ).toString()471  let indexDerivedDev = (472    await fse.readFile(join(nodeEnv, 'index.dev.js'))473  ).toString()474  let browserDerivedProd = (475    await fse.readFile(join(nodeEnv, 'a/index.prod.js'))476  ).toString()477  let browserDerivedDev = (478    await fse.readFile(join(nodeEnv, 'a/index.dev.js'))479  ).toString()480  match(indexDerivedDev, 'if (false) {')481  match(indexDerivedDev, 'if (2+3||true&& 2 + 2) {')482  match(indexDerivedProd, 'if (true) {')483  match(indexDerivedProd, 'if (2+3||false&& 2 + 2) {')484  match(485    indexDerivedProd,486    'if (true&&false\n' +487      '  ||\n' +488      '  true\n' +489      '  &&false\n' +490      '  ||true&&false\n' +491      ') {\n' +492      "  console.log('dev mode')\n" +...

Full Screen

Full Screen

stash.js

Source:stash.js Github

copy

Full Screen

...30    const filePath = path.join(repo.workdir(), fileName);31    let oldContent;32    let stashes = [];33    let stashOid;34    return fse.readFile(filePath)35      .then((content) => {36        oldContent = content;37        return fse.writeFile(filePath, fileContent);38      })39      .then(() => repo.defaultSignature())40      .then((signature) => {41        return Stash.save(repo, signature, stashMessage, 0);42      })43      .then((oid) => {44        stashOid = oid;45        var stashCb = function(index, message, oid) {46          stashes.push({index: index, message: message, oid: oid});47        };48        return Stash.foreach(repo, stashCb);49      })50      .then(() => {51        assert.equal(stashes.length, 1);52        assert.equal(stashes[0].index, 0);53        const expectedMessage = !stashMessage ?54          "WIP on master: 32789a7 Fixes EJS not being installed via NPM" :55          "On master: " + stashMessage;56        assert.equal(stashes[0].message, expectedMessage);57        assert.equal(stashes[0].oid.toString(), stashOid.toString());58        return Stash.drop(repo, 0);59      })60      .then(() => {61        stashes = [];62        var stashCb = (index, message, oid) => {63          stashes.push({index: index, message: message, oid: oid});64        };65        return Stash.foreach(repo, stashCb);66      })67      .then(() => {68        assert.equal(stashes.length, 0);69      })70      .catch((e) => {71        return fse.writeFile(filePath, oldContent)72          .then(() => {73            return Promise.reject(e);74          });75      });76  }77  it("can save and drop a stash", function() {78    return saveDropStash(this.repository, "stash test");79  });80  it("can save a stash with no message and drop it", function() {81    return saveDropStash(this.repository, null);82  });83  it("can save and pop a stash", function() {84    const fileNameA = "README.md";85    const fileNameB = "install.js";86    let oldContentA;87    let oldContentB;88    const fileContent = "Cha-cha-cha-chaaaaaangessssss";89    const repo = this.repository;90    const filePathA = path.join(repo.workdir(), fileNameA);91    const filePathB = path.join(repo.workdir(), fileNameB);92    const stashMessage = "stash test";93    return fse.readFile(filePathA, "utf-8")94      .then((content) => {95        oldContentA = content;96        return fse.writeFile(filePathA, fileContent);97      })98      .then(() => {99        return fse.readFile(filePathB, "utf-8");100      })101      .then((content) => {102        oldContentB = content;103        return fse.writeFile(filePathB, fileContent);104      })105      .then(() => repo.defaultSignature())106      .then((signature) => {107        return Stash.save(repo, signature, stashMessage, 0);108      })109      .then(() => {110        return fse.readFile(filePathA, "utf-8");111      })112      .then((content) => {113        assert.equal(oldContentA, content);114        return fse.readFile(filePathB, "utf-8");115      })116      .then((content) => {117        assert.equal(oldContentB, content);118        return Stash.pop(repo, 0);119      })120      .then(() => {121        return fse.readFile(filePathA, "utf-8");122      })123      .then((content) => {124        assert.equal(fileContent, content);125        return fse.readFile(filePathB, "utf-8");126      })127      .then((content) => {128        assert.equal(fileContent, content);129      });130  });131  it("can save a stash, change files, and fail to pop stash", function() {132      const fileName = "README.md";133      const fileContent = "Cha-cha-cha-chaaaaaangessssss";134      const fileContent2 = "Somewhere over the repo, changes were made.";135      const repo = this.repository;136      const filePath = path.join(repo.workdir(), fileName);137      let oldContent;138      const stashMessage = "stash test";139      return fse.readFile(filePath)140        .then((content) => {141          oldContent = content;142          return fse.writeFile(filePath, fileContent);143        })144        .then(() => repo.defaultSignature())145        .then((signature) => {146          return Stash.save(repo, signature, stashMessage, 0);147        })148        .then(() => {149          return fse.writeFile(filePath, fileContent2);150        })151        .then(() => {152          return Stash.pop(repo, 0);153        })154        .catch((reason) => {155          if (reason.message !== "1 conflict prevents checkout") {156            throw reason;157          } else {158            return Promise.resolve();159          }160        });161  });162  it("can save, apply, then drop the stash", function() {163      const fileName = "README.md";164      const fileContent = "Cha-cha-cha-chaaaaaangessssss";165      const repo = this.repository;166      const filePath = path.join(repo.workdir(), fileName);167      let oldContent;168      const stashMessage = "stash test";169      return fse.readFile(filePath)170        .then((content) => {171          oldContent = content;172          return fse.writeFile(filePath, fileContent);173        })174        .then(() => repo.defaultSignature())175        .then((signature) => {176          return Stash.save(repo, signature, stashMessage, 0);177        })178        .then(() => {179          return Stash.apply(repo, 0);180        })181        .then(() => {182          return Stash.drop(repo, 0);183        }, () => {184          throw new Error("Unable to drop stash after apply.");185        })186        .then(() => {187          return Stash.drop(repo, 0);188        })189        .catch((reason) => {190          if (reason.message !== "reference 'refs/stash' not found") {191            throw reason;192          }193        });194  });195  it("can save multiple stashes and pop an arbitrary stash", function() {196    const fileName = "README.md";197    const fileContentA = "Hi. It's me. I'm the dog. My name is the dog.";198    const fileContentB = "Everyone likes me. I'm cute.";199    const fileContentC =200      "I think I will bark at nothing now. Ba. Ba. Baba Baba.";201    const repo = this.repository;202    const filePath = path.join(repo.workdir(), fileName);203    let oldContent;204    const stashMessageA = "stash test A";205    const stashMessageB = "stash test B";206    const stashMessageC = "stash test C";207    const writeAndStash = (path, content, message) => {208      return fse.writeFile(path, content)209        .then(() => repo.defaultSignature())210        .then((signature) => {211          return Stash.save(repo, signature, message, 0);212        });213    };214    return fse.readFile(filePath, "utf-8")215      .then((content) => {216        oldContent = content;217        return writeAndStash(filePath, fileContentA, stashMessageA);218      })219      .then(() => {220        return writeAndStash(filePath, fileContentB, stashMessageB);221      })222      .then(() => {223        return writeAndStash(filePath, fileContentC, stashMessageC);224      })225      .then(() => {226        return fse.readFile(filePath, "utf-8");227      })228      .then((content) => {229        assert.equal(oldContent, content);230        return Stash.pop(repo, 1);231      })232      .then(() => {233        return fse.readFile(filePath, "utf-8");234      })235      .then((content) => {236        assert.equal(fileContentB, content);237      });238  });...

Full Screen

Full Screen

file.js

Source:file.js Github

copy

Full Screen

...48      const message = 'test info';49      const prepared = logger.prepareMessage(message, 'info');50      await logger.info(message);51      const last = logger.getLastFile();52      const content = await fse.readFile(last.filePath);53      assert.isNotOk(content.toString().match(prepared));54    }); 55    it('should write the info message', async function () {56      logger.level = 'info';57      const message = 'test info';58      const prepared = logger.prepareMessage(message, 'info');59      await logger.info(message);60      const last = logger.getLastFile();61      const content = await fse.readFile(last.filePath);62      assert.isOk(content.toString().match(prepared));63    });     64  });65  describe('.warn()', function () { 66    it('should write nothing', async function () {67      logger.level = 'error';68      const message = 'test warn';69      const prepared = logger.prepareMessage(message, 'warn');70      await logger.warn(message);71      const last = logger.getLastFile();72      const content = await fse.readFile(last.filePath);73      assert.isNotOk(content.toString().match(prepared));74    }); 75    it('should write the warn message', async function () {76      logger.level = 'warn';77      const message = 'test warn';78      const prepared = logger.prepareMessage(message, 'warn');79      await logger.warn(message);80      const last = logger.getLastFile();81      const content = await fse.readFile(last.filePath);82      assert.isOk(content.toString().match(prepared));83    }); 84  });85  describe('.error()', function () { 86    it('should write nothing', async function () {87      logger.level = false;88      const message = 'test error';89      const prepared = logger.prepareMessage(message, 'error');90      await logger.error(message);91      const last = logger.getLastFile();92      const content = await fse.readFile(last.filePath);93      assert.isNotOk(content.toString().match(prepared));94    }); 95    it('should write the error message', async function () {96      logger.level = 'error';97      const message = 'test error';98      const prepared = logger.prepareMessage(message, 'error');99      await logger.error(message);100      const last = logger.getLastFile();101      const content = await fse.readFile(last.filePath);102      assert.isOk(content.toString().match(prepared));103    }); 104  });105  describe('.log()', function () { 106    it('should write in a new file', async function () {107      logger.level = 'info';108      const message = 'test';109      const first = logger.getLastFile();110      logger.options.fileMaxSize = first.stat.size;111      const prepared = logger.prepareMessage(message, 'info');112      await logger.info(message);113      const last = logger.getLastFile();114      const content = await fse.readFile(last.filePath);115      assert.notEqual(first.filePath, last.filePath, 'check the file');116      assert.equal(content.toString(), prepared + '\n', 'check the content');117    }); 118    it('should add messages in parallel', async function () {119      logger.options.fileMaxSize = '10mb';120      const messages = [];121      const p = []122      123      for(let i = 1; i < 10; i++) {124        messages.push('$$' + i);125        p.push(logger.info(messages[messages.length - 1]));126      }127      await Promise.all(p);128      const last = logger.getLastFile();129      const content = (await fse.readFile(last.filePath)).toString();130      131      for(let i = 0; i < messages.length; i++) {132        assert.isOk(content.indexOf(messages[i]) >= 0);133      }134    }); 135  });136  describe('.addNewFile()', function () { 137    it('should create a new file', async function () {138      const files = await fse.readdir(folder);139      const prev = logger.getLastFile();140      const file = await logger.addNewFile();141      const last = logger.getLastFile();142      assert.equal(files.length + 1, (await fse.readdir(folder)).length, 'check the count');143      assert.equal(file.index, prev.index + 1, 'check the index');...

Full Screen

Full Screen

dir-generate.test.js

Source:dir-generate.test.js Github

copy

Full Screen

...35      fse.readdir(path.join(dirPath, 'hello'), function (err, files) {36        should.not.exist(err);37        check();38      });39      fse.readFile(path.join(dirPath, 'hello', '123.txt'), function (err, files) {40        should.not.exist(err);41        check();42      });43      fse.readdir(path.join(dirPath, 'hello', 'ok'), function (err, files) {44        should.not.exist(err);45        check();46      });47      fse.readFile(path.join(dirPath, 'hello', 'ok', 'abc.md'), function (err, files) {48        should.not.exist(err);49        check();50      });51      fse.readFile(path.join(dirPath, 'hello', 'ok', 'good.js'), function (err, files) {52        should.not.exist(err);53        check();54      });55    });56  });57  describe('should run error', function () {58    it('Arguments wrong.', function (done) {59      dg.run(null, null, function (err) {60        err.message.should.equal('Arguments wrong.');61        done();62      });63    });64    it('fse.readFile', function (done) {65      mm.error(fse, 'readFile', 'mock error');66      dg.run(filePath, dirPath, function (err) {67        should(err).Error;68        done();69      });70    });71    it('fse.ensureDir', function (done) {72      mm.error(fse, 'ensureDir', 'mock error');73      dg.run(filePath, dirPath, function (err) {74        should(err).Error;75        done();76      });77    });78  });79  it('should run with JSON ok', function (done) {80    var num = 0;81    function check () {82      if(!--num) {83        done();84      }85    }86    dg.run(filePath2, dirPath, function (err, dirPath) {87      should.not.exist(err);88      num += 5;89      fse.readdir(path.join(dirPath, 'hello'), function (err, files) {90        should.not.exist(err);91        check();92      });93      fse.readFile(path.join(dirPath, 'hello', '123.txt'), function (err, files) {94        should.not.exist(err);95        check();96      });97      fse.readdir(path.join(dirPath, 'hello', 'ok'), function (err, files) {98        should.not.exist(err);99        check();100      });101      fse.readFile(path.join(dirPath, 'hello', 'ok', 'abc.md'), function (err, files) {102        should.not.exist(err);103        check();104      });105      fse.readFile(path.join(dirPath, 'hello', 'ok', 'good.js'), function (err, files) {106        should.not.exist(err);107        check();108      });109    });110  });...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1const htpasswdjs = require('../../lib');2const fse = require('fs-extra');3const Htpasswd = require('../../lib/htpasswd');4describe('index', function() {5	const file = 'path/to/htpasswd/file';6	const data = 'htpasswd data string';7	const username = 'username';8	const password = 'password';9	const authResult = 'auth result';10	let htpasswd;11	beforeEach(function() {12		htpasswd = new Htpasswd();13		sandbox.stub(fse, 'readFile').resolves(data);14		sandbox.stub(Htpasswd, 'parse').returns(htpasswd);15	});16	describe('::authenticate', function() {17		beforeEach(function() {18			sandbox.stub(htpasswd, 'authenticate').resolves(authResult);19		});20		it('authenticates against provided htpasswd file', function() {21			return htpasswdjs.authenticate({ username, password, file })22				.then((result) => {23					expect(fse.readFile).to.be.calledOnce;24					expect(fse.readFile).to.be.calledOn(fse);25					expect(fse.readFile).to.be.calledWith(file, 'utf8');26					expect(Htpasswd.parse).to.be.calledOnce;27					expect(Htpasswd.parse).to.be.calledOn(Htpasswd);28					expect(Htpasswd.parse).to.be.calledWith(data);29					expect(htpasswd.authenticate).to.be.calledOnce;30					expect(htpasswd.authenticate).to.be.calledOn(htpasswd);31					expect(htpasswd.authenticate).to.be.calledWith(32						username,33						password34					);35					expect(result).to.equal(authResult);36				});37		});38		it('authenticates against provided htpasswd data', function() {39			return htpasswdjs.authenticate({ username, password, data })40				.then((result) => {41					expect(fse.readFile).to.not.be.called;42					expect(Htpasswd.parse).to.be.calledOnce;43					expect(Htpasswd.parse).to.be.calledOn(Htpasswd);44					expect(Htpasswd.parse).to.be.calledWith(data);45					expect(htpasswd.authenticate).to.be.calledOnce;46					expect(htpasswd.authenticate).to.be.calledOn(htpasswd);47					expect(htpasswd.authenticate).to.be.calledWith(48						username,49						password50					);51					expect(result).to.equal(authResult);52				});53		});54		it('resolves with false if neither file nor data are provided', function() {55			return htpasswdjs.authenticate({ username, password })56				.then((result) => {57					expect(fse.readFile).to.not.be.called;58					expect(Htpasswd.parse).to.not.be.called;59					expect(result).to.be.false;60				});61		});62		it('resolves with false if username is missing', function() {63			return Promise.all([64				htpasswdjs.authenticate({ password, file }),65				htpasswdjs.authenticate({ password, data })66			])67				.then(([ result, otherResult ]) => {68					expect(fse.readFile).to.not.be.called;69					expect(Htpasswd.parse).to.not.be.called;70					expect(result).to.be.false;71					expect(otherResult).to.be.false;72				});73		});74		it('resolves with false if password is missing', function() {75			return Promise.all([76				htpasswdjs.authenticate({ username, file }),77				htpasswdjs.authenticate({ username, data })78			])79				.then(([ result, otherResult ]) => {80					expect(fse.readFile).to.not.be.called;81					expect(Htpasswd.parse).to.not.be.called;82					expect(result).to.be.false;83					expect(otherResult).to.be.false;84				});85		});86	});...

Full Screen

Full Screen

ext.js

Source:ext.js Github

copy

Full Screen

...22    const customExts = [];23    for(const ext of fse.readdirSync("./extensions")) {24        const dir = `./extensions/${ext}`;25        if (!fse.existsSync(`${dir}/package.json`)) continue;26        const packageJSON = JSON.parse((await fse.readFile(`${dir}/package.json`)));27        let packageNLS = {};28        if (fse.existsSync(`${dir}/package.nls.json`)) {29            packageNLS = JSON.parse((await fse.readFile(`${dir}/package.nls.json`)));30        }31        customExts.push({32            customPath: dir,33            packageJSON,34            packageNLS,35            extensionPath: ext,36        });37    }38    return customExts;39}40// add name and version in product.json41async function addRemote(name) {42    const destDir = `./.build/builtInExtensions/${name}`;43    const packageJSON = JSON.parse((await fse.readFile(`${destDir}/package.json`)));44    let packageNLS = {};45    if (fse.existsSync(`${destDir}/package.nls.json`)) {46        packageNLS = JSON.parse((await fse.readFile(`${destDir}/package.nls.json`)));47    }48    49    return {50        customPath: destDir,51        packageJSON,52        packageNLS,53        extensionPath: name,54    };55}56export async function scanExtensions() {57    const allExtensions = [];58    59    chdir("./vscode");60    await getBuiltInExtensions();61    const extensions = scanBuiltinExtensions(EXTENSIONS_ROOT);62    chdir("..");63    allExtensions.push(...extensions);64    65    const product = JSON.parse((await fse.readFile("./product.json")).toString());66    for (const ext of product["builtInExtensions"]) {67        allExtensions.push(await addRemote(ext.name));68    }69    return allExtensions;70}71// customize vscode bundled extensions72export async function getWantedExtensions() {73    const allExtensions = [];74    for (const f of wantExtensions) {75        const dir = `./vscode/extensions/${f}`;76        if (fse.existsSync(dir)) {77            const packageJSON = JSON.parse((await fse.readFile(`${dir}/package.json`)));78            const packageNLS = JSON.parse((await fse.readFile(`${dir}/package.nls.json`)));79            80            allExtensions.push({81                packageJSON,82                packageNLS,83                extensionPath: f84            })85        }86    }87    88    return allExtensions;89}90export async function getExtensions() {91    return [...await scanExtensions(), ...await getCustomExtensions()];92}

Full Screen

Full Screen

index.mjs

Source:index.mjs Github

copy

Full Screen

...8const fontName = 'ascii_small';9async function build() {10	const externalDepsSrc = await Promise.all(Object.keys(externalDeps).map(function (dep) {11		try {12			return fse.readFile(resolve.sync(dep));13		} catch {14			try {15				return fse.readFile(resolve.sync(dep, {16					basedir: resolve.sync('@bitsy/hecks')17				}));18			} catch {19				console.log(`couldn't find dependency '${dep}' in node modules\nyou might want to include it manually in html template`);20			}21		}22	}));23	const title = await fse.readFile('./input/title.txt');24	const gamedata = await fse.readFile('./input/gamedata.bitsy', 'utf8');25	const template = await fse.readFile(bitsyPaths.template[1], 'utf8');26	const fontData = await fse.readFile(bitsyPaths[fontName][1]);27	const css = await getCss('./input/style.css');28	const hacks = await fse.readFile(`./.working/hacks.js`);29	const bitsyScripts = await Promise.all(30		Object.entries(bitsyPaths) // get all the bitsy files31		.filter(([key]) => key.startsWith('@@')) // filter out non-scripts32		.map(async ([key, [, path]]) => [key, await fse.readFile(path)]) // convert to map of promises resolving with [key, script]33	);34	const config = {35		'@@T': title,36		'@@D': Object.values(optimizeOptions).includes(true) ? optimize(gamedata, optimizeOptions) : gamedata,37		"@@C": css,38		'@@N': fontName,39		'@@M': fontData,40		...bitsyScripts.reduce((r, [key, file]) => ({41			...r,42			[key]: file,43		}), {}),44		'</head>': `${externalDepsSrc.concat(hacks).map(s => `<script>\n${s}\n</script>`).join('\n')}\n</head>`,45	};46	const html = Object.entries(config)...

Full Screen

Full Screen

testing.js

Source:testing.js Github

copy

Full Screen

1const fse = require('fs-extra');2const { PokesavDsGen4, fromBuffer, util } = require('./lib');3async function main() {4  // const buf = await fse.readFile('./testdata/diamond.sav', { encoding: null });5  // const buf = await fse.readFile('./testdata/platinum-first-save.sav', { encoding: null });6  const buf = await fse.readFile('./testdata/platinum-piplup-get.sav', { encoding: null });7  // const buf = await fse.readFile('./testdata/soulsilver-first-save.sav', { encoding: null });8  // const buf = await fse.readFile('./testdata/soulsilver-cyndaquil-get.sav', { encoding: null });9  const data = fromBuffer(buf);10  console.log({11    isDiamondPearl: data.isDiamondPearl,12    isPlatinum: data.isPlatinum,13    isHgss: data.isHgss,14    game: PokesavDsGen4.Game[data.game],15    hasBackup: data.hasBackup16  });17  const current = data.generalBlockCurrent;18  console.log('Name', current.trainerName);19  console.log(`Started adventure at ${util.asDate(current.adventureStartTime)}, has ${current.partyPokemon.length} Pokemon in party. Checksum: ${current.footer.checksum.toString(16)}`);20  console.log('Playtime:', current.playtime);21  console.log('Party:');22  for(const pkmn of current.partyPokemon) {...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const fs = require('fs-extra')2describe('My First Test', function() {3  it('Does not do much!', function() {4    cy.contains('type').click()5    cy.url().should('include', '/commands/actions')6    cy.get('.action-email')7      .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.readFile('test.txt').then((text) => {2    console.log(text)3})4cy.writeFile('test.txt', 'Hello World').then(() => {5    console.log('Done')6})7cy.writeFile('test.txt', 'Hello World').then(() => {8    console.log('Done')9})10cy.readFile('test.txt').then((text) => {11    console.log(text)12})

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', () => {2    it('should read a file', () => {3        cy.readFile('file.json').then((file) => {4            console.log(file)5        })6    })7})

Full Screen

Using AI Code Generation

copy

Full Screen

1const fs = require('fs');2const path = require('path');3module.exports = (on, config) => {4  on('task', {5    readTheFile(filePath) {6      return fs.readFileSync(path.resolve(__dirname, filePath), 'utf8')7    }8  })9}10describe('My First Test', () => {11  it('Does not do much!', () => {12    cy.readFile('cypress/fixtures/test.json').then((file) => {13      cy.log(file)14    })15  })16})17{18}19describe('My First Test', () => {20  it('Does not do much!', () => {21    cy.readFile('cypress/fixtures/test.json', 'utf8').then((file) => {22      cy.log(file)23    })24  })25})26{27}28describe('My First Test', () => {29  it('Does not do much!', () => {30    cy.readFile('cypress/fixtures/test.json', 'utf8').then((file) => {31      cy.log(file)32    })33  })34})35{36}37describe('My First Test', () => {38  it('Does not do much!', () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', () => {2    it('should read file', () => {3        cy.readFile('test.txt').then((fileContent) => {4            cy.log(fileContent)5        })6    })7})

Full Screen

Using AI Code Generation

copy

Full Screen

1const path = require("path");2describe("File Read", function () {3  it("Reads the file", function () {4    cy.readFile(path.resolve(__dirname, "test.txt")).then((text) => {5      cy.log(text);6    });7  });8});9describe("File Read", function () {10  it("Reads the file", function () {11    cy.fixture("test.txt").then((text) => {12      cy.log(text);13    });14  });15});

Full Screen

Using AI Code Generation

copy

Full Screen

1const fs = require('fs-extra')2describe('Read from file', function() {3  it('Reads from the file', function() {4    var content = fs.readFileSync('test.txt', 'utf8')5    console.log(content)6  })7})8const fs = require('fs-extra')9beforeEach(function() {10  var content = fs.readFileSync('test.txt', 'utf8')11  console.log(content)12})13const fs = require('fs-extra')14Cypress.Commands.add('readFile', function() {15  var content = fs.readFileSync('test.txt', 'utf8')16  console.log(content)17})

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful