How to use Bluebird.map method in Cypress

Best JavaScript code snippet using cypress

site.js

Source:site.js Github

copy

Full Screen

1const bluebird = require('bluebird');2const path = require('path');3const mkdirp = require('mkdirp-promise');4const yaml = require('node-yaml');5// FIXME: what an ugly mess with writePage? fix it6const helpers = require('./helpers');7const store = require('./store');8//const netlify = require('./netlify_tasks');9const { readLocalizations } = require('./locale_tasks');10const { shopify } = require('./shopify_client');11const { readFrontMatterFiles } = require('./frontmatter_tasks');12const { writeFile, glob } = require('./utils');13const { buildSitemap } = require('./sitemap_tasks');14const { shopService } = require('./shop_service');15// NOT USED16const readPages = async (ctx, locale) => {17  const { source } = ctx;18  const files = await glob(path.join(source, 'content', locale, 'pages', '*.yml'));19  const items = await bluebird.map(files, file => {20    return yaml.read(file)21      .then(content => {22        const fileKey = path.basename(file, path.extname(file));23        return {24          key: fileKey,25          slug: fileKey || content.slug,26          ...content27        };28      });29  });30  return items;31};32const readPagesFromDirectory = async (ctx, locale, directory) => {33  const { source } = ctx;34  const files = await glob(path.join(source, 'content', locale, directory, '*.yml'));35  const items = await bluebird.map(files, file => {36    return yaml.read(file)37      .then(content => {38        const fileKey = path.basename(file, path.extname(file));39        const slug = path.join(directory, fileKey);40        return {41          key: fileKey,42          slug: slug || content.slug,43          ...content44        };45      });46  });47  return items;48};49const translateUrlToStaticPath = (ctx, destPath) => {50  const { dest } = ctx;51  const url = destPath; 52  if(destPath.charAt(0) == '/') destPath = destPath.substr(1);53  destPath = path.join(dest, destPath);54  const extension = path.extname(destPath);55  if(!extension) {56    destPath = path.join(destPath, 'index.html');57  }58  const basePath = path.dirname(destPath);59  return {60    url,61    basePath,62    filePath: destPath63  };64};65const writePageVersion = async (ctx, page, url, filePath, templateContext, templateFunction, isAliased) => {66  let renderContext = Object.assign({}, templateContext, {67    path: url,68    currentUrl: url, 69    alias: isAliased === true,70    canonicalUrl: page.__canonicalUrl,71    page72  });73  const sitemapData = {74    slug: page.slug,75    url,76    //meta: templateContext.doc77  };78  if(page.sitemap) {79    Object.assign(sitemapData, page.sitemap);80  }81  if(isAliased) {82    sitemapData.isAlias = true;83  }84  if(!page.__versions) page.__versions = [];85  page.__versions.push(url);86  store.sitemap.push(sitemapData);87  return await writeFile(filePath, templateFunction(renderContext));88};89const writePage = async (ctx, page) => {90  const { url, template, slug } = page;91  const { basePath, filePath } = translateUrlToStaticPath(ctx, url);92  page.__file = filePath;93  page.__canonicalUrl = url;94  console.log('[writePage] writing ', slug, template, filePath, url);95  if(false && page.isFrontmatter) {96    //await readFrontMatter(page);97  }98  const templateContext = Object.assign({}, ctx.baseTemplateContext, { 99    slug,100    templateName: template,101    page102  });103  const templateFunction = await ctx.templates[template];104  if(!templateFunction) {105    throw new Error(`Invalid template ${template} for slug ${slug}`);106  }107  const aliases = (page.aliases || []).map(a => {108    return translateUrlToStaticPath(ctx, a);109  });110  await bluebird.map([{ basePath }, ...aliases], p => {111    return mkdirp(p.basePath);112  }, { concurrency: 1 });113  await bluebird.map([{ basePath, filePath, url, canonical: true }, ...aliases], version => {114    return writePageVersion(ctx, page, version.url, version.filePath, templateContext, templateFunction, version.canonical !== true);115  }, { concurrency: 1 });116};117const addRedirect = (ctx, from, to) => {118  if(!ctx.redirects) ctx.redirects = [];119  ctx.redirects.push({120    from,121    to122  });123};124// NOT USED125const prepareImages = async (ctx, imagePath) => {126  const { source } = ctx;127  const files = await glob(path.join(source, imagePath, '*'));128  129  return files.map(f => {130    const filePath = path.relative(source, f);131    console.log('found image:', f, source, filePath);132    return {133      url: `/${filePath}`134    };135  });136};137const dumpProducts = async (context, products) => {138  const { dest } = context;139  console.log('Dumping products:', products);140  await writeFile(path.join(dest, 'products.json'), JSON.stringify(products, true, 2));141};142const fetchShopify = async (context) => {143  if(process.env.SKIP_SHOPIFY) return;144  await shopService.initialize();145  if(false) {146    const { collections, products } = await shopify.fetchAllCollectionsWithProductsMapped();147    shopService.addCollections(collections);148    shopService.addProducts(products);149  }150  151  if(false) {152    Object.values(collections).forEach(c => {153      console.log('[Shopify:Collection]', c.id, c.handle, c.title);154    });155    Object.values(products).forEach(c => {156      console.log('[Shopify:Product]', c.id, c.handle, c.title, c.collectionIds);157    });158  }159  if(context.development) {160    await dumpProducts(context, Object.values(shopService.products));161  }162};163const preparePage = async (ctx, page, metadata = {}) => {164  const data = {};165  if(page.slug.indexOf('collections/') === 0) {166    data.template = 'feature';167  }168  if(page.sitemap && metadata.sitemap) {169    data.sitemap = {};170    Object.assign(data.sitemap, metadata.sitemap, page.sitemap);171  } else if(metadata.sitemap) {172    data.sitemap = Object.assign({}, metadata.sitemap);173  }174  return data;175};176const prepareShopCategory = async (ctx, page) => {177  const data = {178    category: page.category,179    slug: `shop/categories/${page.category}`,180    template: 'shop-category',181    url: `/kauppa/kategoria/${page.slug}`,182    products: shopService.getProductsByCategory(page.category)183  };184  return data;185};186const prepareShopCollection = async (ctx, page) => {187  const shopifyCollection = shopService.getCollectionByHandle(page.shopify.collection);188  const data = {189    collection: shopifyCollection,190    slug: `shop/${page.slug}`,191    template: 'shop-category',192    url: `/kauppa/mallisto/${shopifyCollection.handle}`,193    products: shopService.getCollectionProducts(shopifyCollection.id),194    hero: null195  };196  //console.log('prepareShopCollection', data.slug, shopifyCollection.id, data.products);197  return data;198};199const prepareProduct = async (ctx, page) => {200  const { productId, collectionId, collectionPageSlug } = page;201  const product = shopService.getProduct(productId);202  //const collection = shopService.getCollection(collectionId);203  const collectionPage = store.getCollection(collectionPageSlug);204  const titleParts = [product.fullTitle];205  if(collectionPage.productType) {206    titleParts.unshift(`${collectionPage.productType}:`);207  }208  const data = {209    template: 'product-details',210    slug: `products/${product.handle}`,211    //product,212    //collection,213    headTitle: titleParts.join(' '),214    description: product.metaDescription,215    ogImage: product.image,216    isProduct: true,217    product: {218      id: productId,219      collectionId: collectionId,220      image: shopService.getProductImage(product),221      title: product.title,222      content: product.body_html,223      metafields: product.metafields224    }225  };226  return data;227};228const siteBuilder = module.exports = {229  async buildSite(ctx) {230    const { locales } = ctx;231    // fetch shopify data232    await fetchShopify(ctx);233    await bluebird.map(locales, locale => {234      return siteBuilder.buildSiteVersion(ctx, locale);235    }, { concurrency: 1 });236    //await netlify.setupAdmin(ctx); 237    238    // FIXME: add sitemap generation239  },240  async buildSiteVersion(ctx, locale) {241    ctx.store = store;242    ctx.shopService = shopService;243    const texts = await readLocalizations(ctx, locale);244    store.texts = texts;245    246    // read yaml files247    const [ collections, materials ] = await bluebird.all([248      readPagesFromDirectory(ctx, locale, 'collections'),249      readPagesFromDirectory(ctx, locale, 'materials')250    ]);251    store.collections = collections;252    store.materials = materials;253    const pages = await readFrontMatterFiles(ctx, path.join('content', locale, 'markdown/**/*.md'));254    const yamlPages = await readPages(ctx, locale);255    store.pages = [ ...pages, ...yamlPages ];256    // generate template context257    ctx.baseTemplateContext = {258      ...texts,259      ...helpers(ctx),260      locale,261      site: ctx.site,262      shop: ctx.shopService,263      store,264    };265    266    // compile collections267    await bluebird.map(store.collections, x => {268      return preparePage(ctx, x, { sitemap: { prio: 0.9 } })269        .then(data => writePage(ctx, { ...x, ...data }));270    }, { concurrency: 5 });271    // compile material pages272    await bluebird.map(store.materials, x => {273      return preparePage(ctx, x, { sitemap: { ignore: true } })274        .then(data => writePage(ctx, { ...x, ...data }));275    }, { concurrency: 5 });276    // compile pages277    await bluebird.map(store.pages, x => {278      return preparePage(ctx, x, { sitemap: { prio: 1 } })279        .then(data =>  writePage(ctx, { ...x, ...data }));280    }, { concurrency: 5 });281    // compile products282    await bluebird.map(shopService.buildQueue, x => {283      return prepareProduct(ctx, x)284        .then(data => writePage(ctx, { ...x, ...data, sitemap: { prio: 0.9 } }));285    }, { concurrency: 5 });286    //console.log('Product Categories:', shopService.categories);287    //console.log('Store Categories:', store.shopCategories);288    await bluebird.map(Object.entries(store.shopCategories), y => {289      const [ k, x ] = y;290      return prepareShopCategory(ctx, { ...x, category: k })291        .then(data => writePage(ctx, { ...x, ...data, sitemap: { prio: 0.9 } }));292    }, { concurrency: 5 });293    console.log('Product Collections:', store.productCollections);294    await bluebird.map(store.collections.filter(x => x.shopify && x.released), x => {295      return prepareShopCollection(ctx, x)296        .then(data => writePage(ctx, { ...x, ...data, sitemap: { prio: 0.9 } }));297    }, { concurrency: 5 });298    await buildSitemap(ctx, store);299  }...

Full Screen

Full Screen

20180329220015_init.js

Source:20180329220015_init.js Github

copy

Full Screen

1"use strict";2const bluebird = require('bluebird');3exports.up = function(knex, Promise) {4  return Promise.resolve()5    .then(createTeamsTable)6    .then(createUsersTable)7    .then(createLeaguesTable)8    .then(createInscriptionsTable)9    .then(createTournamentsTable)10    .then(createStagesTable)11    .then(createMatchesTable)12    .then(createBetsTable)13    .then(insertTeams)14    .then(insertUsers)15    .then(insertLeagues)16    .then(insertInscriptions)17    .then(insertTournaments)18    .then(insertStages)19    .then(insertMatches)20    .then(insertBets)21  ;22  // ---23  // CREATES24  // ---25  function createTeamsTable() {26    return knex.schema.createTable('teams', function(table) {27      table.increments('id').primary().unsigned();28      table.string('name');29    });30  }31  function createUsersTable() {32    return knex.schema.createTable('users', function(table) {33      table.increments('id').primary().unsigned();34      table.string('username').unique();35      table.timestamps();36    });37  }38  function createLeaguesTable() {39    return knex.schema.createTable('leagues', function(table) {40      table.increments('id').primary().unsigned();41      table.string('name');42    })43  }44  function createInscriptionsTable() {45    return knex.schema.createTable('inscriptions', function(table) {46      table.increments('id').primary().unsigned();47      table.integer('user_id').unsigned().references('id').inTable('users');48      table.integer('league_id').unsigned().references('id').inTable('leagues');49      table.timestamps();50      table.unique(['user_id', 'league_id']);51    })52  }53  function createTournamentsTable() {54    return knex.schema.createTable('tournaments', function(table) {55      table.increments('id').primary().unsigned();56      table.string('name');57    })58  }59  function createStagesTable() {60    return knex.schema.createTable('stages', function(table) {61      table.increments('id').primary().unsigned();62      table.integer('tournament_id').unsigned().references('id').inTable('tournaments');63      table.string('name');64    })65  }66  function createMatchesTable() {67    return knex.schema.createTable('matches', function(table) {68      table.increments('id').primary().unsigned();69      table.integer('local_id').unsigned().references('id').inTable('teams');70      table.integer('visitor_id').unsigned().references('id').inTable('teams');71      table.integer('stage_id').unsigned().references('id').inTable('stages');72      table.dateTime('date');73      table.string('place');74    })75  }76  function createBetsTable() {77    return knex.schema.createTable('bets', function(table) {78      table.increments('id').primary().unsigned();79      table.integer('user_id').unsigned().references('id').inTable('users');80      table.integer('match_id').unsigned().references('id').inTable('matches');81      table.integer('local_score');82      table.integer('visitor_score');83      table.timestamps();84      table.unique(['user_id', 'match_id']);85    })86  }87  // ---88  // INSERTS89  // ---90  function insertTeams() {91    const teams = [92      'Rusia',93      'Brasil',94      'Irán',95      'Japón',96      'México',97      'Bélgica',98      'Corea del Sur',99      'Arabia Saudita',100      'Alemania',101      'Inglaterra',102      'España',103      'Nigeria',104      'Costa Rica',105      'Polonia',106      'Egipto',107      'Islandia',108      'Serbia',109      'Francia',110      'Portugal',111      'Uruguay',112      'Argentina',113      'Colombia',114      'Panamá',115      'Senegal',116      'Marruecos',117      'Túnez',118      'Suiza',119      'Croacia',120      'Suecia',121      'Dinamarca',122      'Australia',123      'Perú'124    ].map(name => ({name}));125    return bluebird.map(teams, team => knex('teams').insert(team));126  }127  function insertUsers() {128    const users = [129      'user1',130      'user2',131      'user3'132    ].map(username => ({username}));133    return bluebird.map(users, user => knex('users').insert(user));134  }135  function insertLeagues() {136    const leagues = [137      'Liga default'138    ].map(name => ({name}));139    return bluebird.map(leagues, league => knex('leagues').insert(league));140  }141  //   return knex.schema.createTable('inscriptions', function(table) {142  //     table.increments('id').primary().unsigned();143  //     table.integer('user_id').unsigned().references('id').inTable('users');144  //     table.integer('league_id').unsigned().references('id').inTable('leagues');145  //     table.timestamps();146  //     table.unique(['user_id', 'league_id']);147  function insertInscriptions() {148    const inscriptions = [{149      user_id:   1,150      league_id: 1151    }, {152      user_id:   2,153      league_id: 1154    }, {155      user_id:   3,156      league_id: 1157    }];158    return bluebird.map(inscriptions, inscription => knex('inscriptions').insert(inscription));159  }160  function insertTournaments() {161    const tournaments = [162      'Mundial 2018'163    ].map(name => ({name}));164    return bluebird.map(tournaments, tournament => knex('tournaments').insert(tournament));165  }166  function insertStages() {167    const stages = [168      'Grupo A',169      'Grupo B',170      'Grupo C',171      'Grupo D',172      'Grupo E',173      'Grupo F',174      'Grupo G',175      'Grupo H'176    ].map(name => ({177      name,178      tournament_id: 1179    }));180    return bluebird.map(stages, stage => knex('stages').insert(stage));181  }182  function insertMatches() {183    const matches = [{184      local_id:   1,185      visitor_id: 2,186      stage_id:   1,187      date:       new Date(),188      place:      'cancha 1'189    }, {190      local_id:   3,191      visitor_id: 4,192      stage_id:   1,193      date:       new Date(),194      place:      'cancha 2'195    }, {196      local_id:   5,197      visitor_id: 6,198      stage_id:   2,199      date:       new Date(),200      place:      'cancha 3'201    }, {202      local_id:   7,203      visitor_id: 8,204      stage_id:   2,205      date:       new Date(),206      place:      'cancha 4'207    }];208    return bluebird.map(matches, match => knex('matches').insert(match));209  }210  function insertBets() {211    const bets = [{212      user_id:       1,213      match_id:      1,214      local_score:   3,215      visitor_score: 0216    }, {217      user_id:       1,218      match_id:      2,219      local_score:   1,220      visitor_score: 2221    }, {222      user_id:       1,223      match_id:      3,224      local_score:   0,225      visitor_score: 0226    }, {227      user_id:       2,228      match_id:      1,229      local_score:   2,230      visitor_score: 5231    }];232    return bluebird.map(bets, bet => knex('bets').insert(bet));233  }234};235exports.down = function(knex, Promise) {236  const tables = [237    'inscriptions',238    'bets',239    'users',240    'leagues',241    'matches',242    'teams',243    'stages',244    'tournaments'245  ];246  return bluebird.map(tables, table => knex.schema.dropTable(table));...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1const fs = require('fs').promises;2const bluebird = require('bluebird');3const AnimeModel = require('./models/anime');4const ExternalLinkModel = require('./models/externalLink');5const ReviewModel = require('./models/review');6const CharacterModel = require('./models/character');7const StudioModel = require('./models/studios');8const GenreModel = require('./models/genre');9const TagModel = require('./models/tag');10const ThemeModel = require('./models/theme');11const linkOf = require('./models/link_of');12const reviewOf = require('./models/reviewOf');13const characterOf = require('./models/characterOf');14const fromStudio = require('./models/fromStudio');15const inGenre = require('./models/inGenre');16const inTag = require('./models/inTag');17const inTheme = require('./models/inTheme');18const start = async () => {19  const bresult = JSON.parse(await fs.readFile('./result.json')).result;20  const insert = await bluebird.map(21    bresult,22    (result, index) => {23      console.log(index);24      const task = async () => {25        try {26          console.log('try');27          const batch = await bluebird.props({28            anime: AnimeModel.save({29              romajiTitle: result.title.romaji,30              englishTitle: result.title.english,31              nativeTitle: result.title.native,32              description: result.description,33              startDate: new Date(34                `${result.startDate.year}-${result.startDate.month}-${result.startDate.day}`35              ),36              endDate:37                result.endDate.year && result.endDate.month && result.endDate.day38                  ? new Date(`${result.endDate.year}-${result.endDate.month}-${result.endDate.day}`)39                  : null,40              nbEpisodes: result.episodes,41              trailer: `https://www.youtube.com/watch?v=${result.trailer.id}`,42              xLargeCover: result.coverImage.extraLarge,43              largeCover: result.coverImage.large,44              mediumCover: result.coverImage.medium,45              avgScore: result.averageScore,46              popularity: result.popularity47            }),48            ExternalLink: bluebird.map(result.externalLinks, el => {49              return ExternalLinkModel.save(el);50            }),51            reviews: bluebird.map(result.reviews.nodes, el => {52              const rev = { score: el.score, summary: el.summary };53              return ReviewModel.save(rev);54            }),55            characters: bluebird.map(result.characters.nodes, el => {56              const rev = {57                firstName: el.name.first,58                lastName: el.name.last || null,59                nativeName: el.name.native,60                largeImage: el.image.large,61                mediumImage: el.image.medium,62                description: el.description63              };64              return CharacterModel.save(rev);65            }),66            studio: StudioModel.save({67              name: result.studios.nodes[0].name,68              url: result.studios.nodes[0].siteUrl69            }),70            genres: bluebird.map(result.genres, el => {71              return GenreModel.save({ name: el });72            }),73            tags: bluebird.map(result.tags, el => {74              return TagModel.save({ name: el.name, description: el.description });75            }),76            themes: bluebird.map(result.tags, el => {77              return ThemeModel.save({ name: el.category });78            })79          });80          const { anime, ExternalLink, reviews, characters, studio, genres, tags, themes } = batch;81          const formatedTags = batch.tags.map(tag => {82            const augmentedTag = { ...tag };83            const originalTags = result.tags;84            const { category } = originalTags.find(elem => elem.name === tag.record.name);85            const theme = themes.find(elem => elem.record.name === category);86            augmentedTag.themeId = theme.record.themeId;87            augmentedTag.themeBookmarks = theme.bookmarks;88            return augmentedTag;89          });90          const linked = await bluebird.props({91            linkOf: bluebird.map(ExternalLink, el => {92              return linkOf.save({93                from: el.record.externalLinkId,94                to: anime.record.animeId,95                bookmarks: [...anime.bookmarks, ...el.bookmarks]96              });97            }),98            reviewOf: bluebird.map(reviews, el => {99              return reviewOf.save({100                from: el.record.reviewId,101                to: anime.record.animeId,102                bookmarks: [...anime.bookmarks, ...el.bookmarks]103              });104            }),105            characterOf: bluebird.map(characters, el => {106              return characterOf.save({107                from: el.record.characterId,108                to: anime.record.animeId,109                bookmarks: [...anime.bookmarks, ...el.bookmarks]110              });111            }),112            fromStudio: fromStudio.save({113              from: anime.record.animeId,114              to: studio.record.studioId,115              bookmarks: [...anime.bookmarks, ...studio.bookmarks]116            }),117            inGenre: bluebird.map(genres, el => {118              return inGenre.save({119                from: anime.record.animeId,120                to: el.record.genreId,121                bookmarks: [...anime.bookmarks, ...el.bookmarks]122              });123            }),124            inTheme: bluebird.map(formatedTags, el => {125              return inTheme.save({126                from: el.record.tagId,127                to: el.themeId,128                bookmarks: [...el.bookmarks, ...el.themeBookmarks]129              });130            }),131            inTag: bluebird.map(tags, el => {132              return inTag.save({133                from: anime.record.animeId,134                to: el.record.tagId,135                bookmarks: [...anime.bookmarks, ...el.bookmarks]136              });137            })138          });139        } catch (e) {140          console.log(141            result,142            typeof new Date(`${result.endDate.year}-${result.endDate.month}-${result.endDate.day}`)143          );144          console.log(e, 'lfdklk');145        }146      };147      return task();148    },149    { concurrency: 20 }150  );151};...

Full Screen

Full Screen

swap.js

Source:swap.js Github

copy

Full Screen

...24  describe('Quote', () => {25    it('should refuse quote with invalid amount', async function () {26      this.timeout(0)27      const request = chai.request(app()).keepOpen()28      return Bluebird.map(contexts, (context) =>29        request30          .post('/api/swap/order')31          .send({32            from: context.from,33            to: context.to,34            fromAmount: 1000035          })36          .then((res) => res.should.have.status(400))37      ).then(() => request.close())38    })39    it('should accept a quote', async function () {40      this.timeout(0)41      const request = chai.request(app()).keepOpen()42      return Bluebird.map(contexts, (context) => requestQuote(context, request)).then(() => request.close())43    })44    it('should get quote by id', async function () {45      this.timeout(0)46      const request = chai.request(app()).keepOpen()47      return Bluebird.map(contexts, (context) => testQuote(context, request)).then(() => request.close())48    })49    it('should throw an error when quote id is incorrect', async function () {50      this.timeout(0)51      const request = chai.request(app()).keepOpen()52      return Bluebird.map(contexts, () =>53        request.get('/api/swap/order/abc').then((res) => res.should.have.status(400))54      ).then(() => request.close())55    })56  })57  describe('Swap', () => {58    it('should confirm the quote', async function () {59      this.timeout(0)60      const request = chai.request(app()).keepOpen()61      async function fundContext(context, request) {62        try {63          await userFund(context, request)64        } catch (e) {65          if (e.name === 'RescheduleError') {66            return wait(5000).then(() => fundContext(context, request))67          }68          throw e69        }70      }71      return Bluebird.map(contexts, async (context) => {72        await userInitiate(context, request)73        await fundContext(context, request)74      }).then(() => request.close())75    })76    it('should reject duplicate fromFundHash', async function () {77      this.timeout(0)78      const request = chai.request(app()).keepOpen()79      return Bluebird.map(contexts, async (context) => {80        const ctx = {81          from: context.from,82          to: context.to,83          fromAmount: context.fromAmount84        }85        await requestQuote(ctx, request)86        ctx.fromAddress = context.fromAddress87        ctx.toAddress = context.toAddress88        ctx.secretHash = context.secretHash89        ctx.fromFundHash = context.fromFundHash90        return updateAgentOrder(ctx, request, true)91      }).then(() => request.close())92    })93    it('should verify funding of the quote', async function () {94      this.timeout(0)95      const request = chai.request(app()).keepOpen()96      return Bluebird.map(contexts, (context) => verifyAgentInitiation(context, request)).then(() => request.close())97    })98    it('should not allow update to already funded quote', async function () {99      this.timeout(0)100      const request = chai.request(app()).keepOpen()101      return Bluebird.map(contexts, (context) =>102        request103          .post(`/api/swap/order/${context.orderId}`)104          .send({105            fromAddress: '0x572E7610B0FC9a00cb4A441F398c9C7a5517DE32',106            toAddress: 'bcrt1qjywshhj05s0lan3drpv9cu7t595y7k5x00ttf8',107            fromFundHash: '98241f985c22fa523028f5fbc7d61305f8ee11fce7c334f015a470f292624948',108            secretHash: '122f75aa0dbfb90db7984fe82400888443eacca84d388c7a93d976c640864e01'109          })110          .then((res) => res.should.have.status(400))111      ).then(() => request.close())112    })113    if (!reject) {114      it('should reciprocate by funding the swap', async function () {115        this.timeout(0)116        await Bluebird.map(contexts, (context) => approveOrder(context), {117          concurrency: 2118        })119        const request = chai.request(app()).keepOpen()120        return Bluebird.map(contexts, (context) => verifyAgentFunding(context, request)).then(() => request.close())121      })122      it("should find the agent's funding tx", async function () {123        this.timeout(0)124        return Bluebird.map(contexts, (context) => findAgentFundingTx(context))125      })126    }127  })128  if (reject) {129    describe('NOOP', () => {130      it('should ignore the swap', async function () {131        this.timeout(0)132        const expectedStatus = 'USER_FUNDED'133        const request = chai.request(app()).keepOpen()134        return Bluebird.map(contexts, (context) => verifyAgentClaimOrRefund(context, request, expectedStatus))135      })136    })137  } else {138    describe(refund ? 'Refund' : 'Claim', () => {139      if (!refund) {140        before(async function () {141          this.timeout(0)142          return Bluebird.map(contexts, (context) => userClaim(context))143        })144      }145      it(`should ${refund ? 'refund' : 'claim'} the swap`, async function () {146        this.timeout(0)147        const expectedStatus = refund ? 'AGENT_REFUNDED' : 'AGENT_CLAIMED'148        const request = chai.request(app()).keepOpen()149        return Bluebird.map(contexts, (context) => verifyAgentClaimOrRefund(context, request, expectedStatus))150      })151    })152  }153  describe('Verify all transactions', () => {154    it('should verify all transactions', async function () {155      this.timeout(0)156      const request = chai.request(app()).keepOpen()157      return Bluebird.map(contexts, (context) => verifyAllTxs(context, request))158    })159  })...

Full Screen

Full Screen

map-series.js

Source:map-series.js Github

copy

Full Screen

1if (false) {2const arr = [];3for(let i in [1,2,3,4,5]) {4	const p =5    new Promise((resolve, reject)=>{6        console.log('promise '+i);7        resolve(i)8    })9    .then((d)=>{10        console.log('i='+i+' .then(): d', d);11    });12    arr.push(p);13}14/*15const p2 = Promise.mapSeries(arr);16console.log(p2);17*/18const bluebird = require('bluebird');19var i = 2;20const bp = new bluebird.Promise((resolve, reject)=>{21    console.log('*promise '+i);22    resolve(i)23})24.then((d)=>{25    console.log('*i='+i+' .then(): d', d);26});27}28// const promise = require('bluebird');29// console.log('promise', promise);30// console.log('bluebird', bluebird);31//promise.mapSeries;32/*33//Create an array of 3 file names which needs to be read and processed34var fileNames = ['test.txt', 'test1.txt', 'test2.txt'];35//Instead of reading them synchronously, we will use promises to read them asynchronously36var filePromises = fileNames.map(function(fileName) {37    38    return promiseFun1(fileName).then(sentences=>{39        console.log('Processing file = ', fileName);40        return wordCount(sentences);41    });42});43require('bluebird').mapSeries(filePromises, function (filePromise) {44    return filePromise;45}).then(numWords=>{46    console.log('Count of all files = ', numWords);47})48.catch(err=> {49    console.log(err);50});51*/52/*53console.log('bluebird.mapSeries', bluebird.mapSeries());54*/55//console.log('bp', bp);56/*57bluebird.mapSeries([bp]).then((d)=>{58    console.log('bluebird.mapSeries .then() d=', d);59});60*/61const bluebird = require('bluebird');62bluebird.mapSeries([100,200], (d)=>{63    console.log('d', d);64    return d+1;65}).then((d)=>{66    console.log('bluebird.mapSeries .then() d=', d);67});68/*69function mapSeries(things, fn) {70    var results = [];71    return Promise.each(things, function(value, index, length) {72        var ret = fn(value, index, length);73        results.push(ret);74        return ret;75    })76    .thenReturn(results)77    .all();78}79Promise.reduce(operations, (i, [query, update]) => {80  return Model.update(query, update);81}, 0);82Promise.series(operations, ([query, update]) => {83  return Model.update(query, update);84});85// https://github.com/petkaantonov/bluebird/issues/13486var arr = [1,2,3,4,5];87Promise.mapSeries(arr, function (itm) {88      console.log('on: ' + itm);89      return Promise.delay(500).then(function() { console.log('off: ' +itm); 90   }).delay(500);91});92// https://codereview.stackexchange.com/questions/177475/iterate-array-with-delay-in-between-using-promise/177560#17756093*/94Promise = bluebird;95/*96var arr = [1,2,3,4,5];97Promise.mapSeries(arr, function (itm) {98      console.log('on: ' + itm);99      return Promise100        .delay(50)101        .then( () => {102            console.log('off: ' +itm); 103        })104        .delay(50);105});106*/107/*108That function returns a promise.109It waits for each promise÷ to finish before starting the next one?110*/111/*112[1,2,3].mapSeries(  (x)=>{return new Promise(...  {x+1}); )113[2,3,4]114*/115var arr = [1,2,3,4,5];116const q = Promise.mapSeries(arr, (itm) => {117      console.log('on: ' + itm);118      119      return new Promise((r,j)=>{120            const waittime = Math.random()*100;121            setTimeout(()=>{122                console.log('waited', waittime, '->', itm);123                if (itm===3) {124                    j(itm+1000);125                    //return;126                }127                r(itm+1000);128                //return itm+100;129            }, waittime);130      })131       .then( (d) => {132            console.log('off: ' +itm+' d:'+d); 133            return -d;134        })135        // we dont get tio promise series's catch        136       .catch( (d) => {137            console.log('inner catch:', d); 138            return d*100;139        });140})141.then((outcome)=>{142    console.log('outcome', outcome);143})144//we neveer need this145.catch((err)=>{146    console.log('promise series catch:', err);147})148// outcome [ -1001, -1002, -1003, -1004, -1005 ]149console.log('q', q);150/*151npm install heapdump 152https://blog.risingstack.com/finding-a-memory-leak-in-node-js/153*/154/*155promise seris:logreseolve & resoleve && resoleve...

Full Screen

Full Screen

bluebird-map-concurrency.js

Source:bluebird-map-concurrency.js Github

copy

Full Screen

...23}24module.exports = {25	meta: {26		docs: {27			description: 'enforce passing a concurrency number to [`Bluebird.map`](http://bluebirdjs.com/docs/api/promise.map.html), for example `Bluebird.map([promise], { concurrency: 5 })`',28			category: 'Best Practices',29		},30	},31	create: function (context) {32		let bluebirdIdentifier33		return {34			VariableDeclarator: function (workNode) {35				if (_.isMatch(workNode, REQUIRE_BLUEBIRD)) {36					bluebirdIdentifier = workNode.id.name37				}38			},39			CallExpression: function (workNode) {40				if (_.isMatch(workNode.callee.property, METHOD_MAP) === false) {41					return null42				}43				const identifier = _.get(workNode, 'callee.object.name')44				if (identifier === undefined) {45					return null46				}47				if (identifier !== 'Promise' && identifier !== bluebirdIdentifier) {48					return null49				}50				if (workNode.arguments.length === 0) {51					return null52				}53				if (workNode.arguments.length < 3) {54					return context.report({55						node: workNode.callee.property,56						message: `Expected ${identifier}.map() to have a concurrency limit.`,57					})58				}59				if (workNode.arguments[2].type !== 'ObjectExpression' || workNode.arguments[2].properties.some(node => node.type === 'Property' && node.key && node.key.type === 'Identifier' && node.key.name === 'concurrency') === false) {60					return context.report({61						node: workNode.arguments[2],62						message: `Expected ${identifier}.map() to have a concurrency limit.`,63					})64				}65			}66		}67	},68	tests: {69		valid: [70			{71				code: `72					const Bluebird = require('bluebird')73					Bluebird.map()74				`,75				parserOptions: { ecmaVersion: 6, sourceType: 'module' },76			},77			{78				code: `79					const Bluebird = require('bluebird')80					Bluebird.map([1, 2, 3], x, { concurrency: 2 })81				`,82				parserOptions: { ecmaVersion: 6, sourceType: 'module' },83			},84		],85		invalid: [86			{87				code: `88					const Bluebird = require('bluebird')89					Bluebird.map([1, 2, 3])90				`,91				parserOptions: { ecmaVersion: 6, sourceType: 'module' },92				errors: [{ message: 'Expected Bluebird.map() to have a concurrency limit.', }]93			},94			{95				code: `96					const Bluebird = require('bluebird')97					Bluebird.map([1, 2, 3], x)98				`,99				parserOptions: { ecmaVersion: 6, sourceType: 'module' },100				errors: [{ message: 'Expected Bluebird.map() to have a concurrency limit.', }]101			},102			{103				code: `104					const Bluebird = require('bluebird')105					Bluebird.map([1, 2, 3], x, {})106				`,107				parserOptions: { ecmaVersion: 6, sourceType: 'module' },108				errors: [{ message: 'Expected Bluebird.map() to have a concurrency limit.', }]109			},110		]111	}...

Full Screen

Full Screen

display-details.js

Source:display-details.js Github

copy

Full Screen

...26  await libuvc.initialize();27  const context = new Context(libuvc, null, null);28  await context.initialize();29  const devices = context.getDeviceList();30  await Bluebird.map(devices, (device) => device.initialize());31  const deviceDescriptors = await Bluebird.map(devices, (device) =>32    device.getDescriptor()33  );34  await Bluebird.map(deviceDescriptors, (deviceDescriptor) =>35    deviceDescriptor.initialize()36  );37  console.log(deviceDescriptors);38  // Bluebird.each(deviceDeviceDescriptors, async deviceDeviceDescriptor => {39  // const device = new Device(40  //   libuvc,41  //   context,42  //   device.vendor.id,43  //   device.product.id,44  //   device.serialNumber,45  //   libuvc46  // );47  // await device.initialize();48  // const deviceHandle = new DeviceHandle(libuvc, device);49  // await deviceHandle.initialize();50  // await deviceHandle.uninitialize();51  // await device.uninitialize();52  // });53  await Bluebird.map(deviceDescriptors, (deviceDescriptor) =>54    deviceDescriptor.uninitialize()55  );56  await Bluebird.map(devices, (device) => device.uninitialize());57  await context.uninitialize();58  await libuvc.uninitialize();59};60const mainWrapper = async () => {61  try {62    await main();63  } catch (error) {64    console.error("main", error);65    process.exitCode = 1;66  }67};68try {69  mainWrapper();70} catch (error) {...

Full Screen

Full Screen

1401-map-promises-transformer.js

Source:1401-map-promises-transformer.js Github

copy

Full Screen

1var tap = require('tap'),2    sinon = require('sinon'),3    transformer = require('../trials/14-map-promises').transformer,4    bluebird = require('bluebird');5process.on('uncaughtException', tap.threw).on('unhandledRejection', tap.threw);6var callback = sinon.stub();7var double = function (i) {8    return new Promise((resolve) => resolve(i*2));9};10var spy = sinon.spy(double);11var list = [];12for(var i=0; i<100; i++) {13    list[i] = i;14}15var expectedResult = [];16for(var i=0; i<100; i++) {17    expectedResult[i] = i*2;18}19sinon.spy(bluebird, 'map');20var promise = transformer(list, double, callback);21tap.ok(promise, 'Was a promise returned?');22tap.ok(promise.then, 'Was a promise returned?');23promise.then((r) => {24    tap.ok(bluebird.map.notCalled, 'Confirm that bluebird.map was not used');25    tap.deepEquals(r, expectedResult, 'Did the call return a properly transformed array?');26    bluebird.map.restore();...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

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

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Promise.map([1, 2, 3], (num) => {2  return new Promise((resolve) => {3    setTimeout(() => {4      resolve(num * 2)5    }, 1000)6  })7}).then((results) => {8  expect(results).to.deep.eq([2, 4, 6])9})10describe('Test', () => {11  it('should test', () => {12    cy.get('h1').should('be.visible')13  })14})15describe('Test', () => {16  it('should test', () => {17    cy.get('h1').should('be.visible')18  })19})20describe('Test', () => {21  it('should test', () => {22    cy.get('h1').should('be.visible')23  })24})25describe('Test', () => {26  it('should test', () => {27    cy.get('h1').should('be.visible')28  })29})30describe('Test', () => {31  it('should test', () => {32    cy.get('h1').should('be.visible')33  })34})35describe('Test', () => {36  it('should test', () => {37    cy.get('h1').should('be.visible')38  })39})40describe('Test', () => {41  it('should test', () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { map } = require('bluebird');2describe('My First Test', () => {3  it('Does not do much!', () => {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

1const Promise = require('bluebird');2Promise.map([1, 2, 3], (num) => {3  return num * 2;4}).then((results) => {5  console.log(results);6});7const Promise = require('bluebird');8describe('Test', () => {9  it('test', () => {10  });11});12const Promise = require('bluebird');13{14  "env": {15  }16}17const Promise = require('bluebird');18Promise.config({19});20{21  "env": {22  },23}24const Promise = require('bluebird');25Promise.config({26});27const Promise = require('bluebird');28Promise.config({29});30const Promise = require('bluebird');31Promise.config({32});33const Promise = require('bluebird');34Promise.config({35});

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('map', {prevSubject: true}, (subject, fn) => {2    return new Cypress.Promise((resolve, reject) => {3        return Promise.map(subject, fn).then(resolve, reject);4    });5});6describe('test', function() {7    it('should do something', function() {8        cy.wrap([1,2,3]).map((item) => {9            return item + 1;10        }).should('deep.equal', [2,3,4]);11    });12});13Cypress.Commands.add('map', {prevSubject: true}, (subject, fn) => {14    return new Cypress.Promise((resolve, reject) => {15        return Promise.map(subject, fn).then(resolve, reject);16    });17});18describe('test', function() {19    it('should do something', function() {20        cy.wrap([1,2,3]).map((item) => {21            return item + 1;22        }).should('deep.equal', [2,3,4]);23    });24});25Cypress.Commands.add('map', {prevSubject: true}, (subject, fn) => {26    return new Cypress.Promise((resolve, reject) => {27        return Promise.map(subject, fn).then(resolve, reject);28    });29});30describe('test', function() {31    it('should do something', function() {32        cy.wrap([1,2,3]).map((item) => {33            return item + 1;34        }).should('deep.equal', [2,3,4]);35    });36});37Cypress.Commands.add('map', {prevSubject: true}, (subject, fn) => {38    return new Cypress.Promise((resolve, reject) => {39        return Promise.map(subject, fn).then(resolve, reject);40    });41});42describe('test', function() {43    it('should do something', function() {44        cy.wrap([1,2,3]).map((item) => {

Full Screen

Using AI Code Generation

copy

Full Screen

1const cypress = require('cypress')2const { map } = require('bluebird')3const { parseConfig } = require('cypress-parallel-tests')4const config = parseConfig()5const { browser, group, spec } = config6const options = {7  config: {8  },9  env: {10  },11}12map(spec, (file) => {13  return cypress.run(options)14})15const { map } = require('bluebird')16const { parseConfig } = require('cypress-parallel-tests')17module.exports = (on, config) => {18  on('task', {19    parallel({ spec, browser }) {20      const config = parseConfig()21      const { group } = config22      return map(spec, (file) => {23        return cypress.run({24          config: {25          },26          env: {27          },28        })29      })30    },31  })32}33Cypress.Commands.add('parallel', (spec, browser) => {34  return cy.task('parallel', { spec, browser })35})36{37  "env": {38  }39}

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', function() {2    it('Test', function() {3        cy.wrap([1, 2, 3]).map(function(value) {4            return value * 2;5        }).then(function(result) {6            expect(result).to.deep.equal([2, 4, 6]);7        });8    });9});10const Bluebird = require('bluebird');11Cypress.Promise = Bluebird;12"devDependencies": {13}

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