Best JavaScript code snippet using cypress
setup.js
Source:setup.js
...29 return fs.pathExists(`./dev/${config.slug}_dev`).then((alreadyInPlace) => {30 if (alreadyInPlace) {31 return Promise.reject(`path './dev/${config.slug}_dev' already exists. It looks like you've already been set up`);32 } else {33 return fs.ensureDir(`./dev/${config.slug}_dev`).then(() => {34 return fs.ensureFile(`./dev/${config.slug}_dev/Manifest.json`).then(() => {35 fs.writeJson(`./dev/${config.slug}_dev/Manifest.json`, manifest).then(() => {36 console.log("'dev' folder built");37 })38 })39 }).then(() => {40 console.log("symlinking assets to dev folder");41 return Promise.all([42 fs.createSymlink("./assets/Fonts", `./dev/${config.slug}_dev/Fonts`, "junction"),43 fs.createSymlink("./assets/Models", `./dev/${config.slug}_dev/Models`, "junction"),44 fs.createSymlink("./assets/Sounds", `./dev/${config.slug}_dev/Sounds`, "junction"),45 fs.createSymlink("./assets/States", `./dev/${config.slug}_dev/States`, "junction"),46 fs.createSymlink("./assets/Templates", `./dev/${config.slug}_dev/Templates`, "junction"),47 fs.createSymlink("./assets/Textures", `./dev/${config.slug}_dev/Textures`, "junction"),48 fs.createSymlink("./assets/Thumbnails", `./dev/${config.slug}_dev/Thumbnails`, "junction"),49 fs.ensureDir(`./dev/${config.slug}_dev/Scripts/node_modules`)50 ])51 }).then(() => {52 console.log("symlinking to Tabletop Playground");53 return fs.createSymlink(`./dev/${config.slug}_dev`, `${localConfig.ttpg_folder}/${config.slug}_dev`, "junction").then(() => {54 console.log("Tabletop Playground is now aware of this project. Huzzah.");55 })56 })57 }58 })59 })60};6162Promise.all([63 fs.ensureDir("./assets/Fonts"),64 fs.ensureDir("./assets/Models"),65 fs.ensureDir("./assets/Sounds"),66 fs.ensureDir("./assets/States"),67 fs.ensureDir("./assets/Templates"),68 fs.ensureDir("./assets/Textures"),69 fs.ensureDir("./assets/Thumbnails"),70]).then(() => {71 return fs.pathExists("./config/local.json").then((doesExist) => {72 if (doesExist) {73 console.log("Local config found, using that");74 return fs.readJson("./config/local.json").then((config) => {75 return setupWorkspace(config);76 });77 } else {78 console.log("no local config found");79 const input = readline.createInterface({80 input: process.stdin,81 output: process.stdout82 })83 return new Promise((resolve, reject) => {
...
e2e-framework.js
Source:e2e-framework.js
...47 * @param {Object} options48 */49const prepareContentFolder = ({contentFolder, redirectsFile = true, routesFile = true}) => {50 const contentFolderForTests = contentFolder;51 fs.ensureDir(contentFolderForTests);52 fs.ensureDir(path.join(contentFolderForTests, 'data'));53 fs.ensureDir(path.join(contentFolderForTests, 'themes'));54 fs.ensureDir(path.join(contentFolderForTests, 'images'));55 fs.ensureDir(path.join(contentFolderForTests, 'logs'));56 fs.ensureDir(path.join(contentFolderForTests, 'adapters'));57 fs.ensureDir(path.join(contentFolderForTests, 'settings'));58 // Copy all themes into the new test content folder. Default active theme is always casper.59 // If you want to use a different theme, you have to set the active theme (e.g. stub)60 fs.copySync(61 path.join(__dirname, 'fixtures', 'themes'),62 path.join(contentFolderForTests, 'themes')63 );64 if (redirectsFile) {65 redirectsUtils.setupFile(contentFolderForTests, '.yaml');66 }67 if (routesFile) {68 fs.copySync(69 path.join(__dirname, 'fixtures', 'settings', 'routes.yaml'),70 path.join(contentFolderForTests, 'settings', 'routes.yaml')71 );...
domain-manager.js
Source:domain-manager.js
...8 describe('`scanDomains()` method', () => {9 it('should build an array of domains and paths', () => {10 const domainsDirectory = path.resolve(config.get('multiDomain.directory'))11 return Promise.all([12 fs.ensureDir(path.join(domainsDirectory, 'localhost')),13 fs.ensureDir(path.join(domainsDirectory, 'testdomain.com'))14 ]).then(() => {15 const domains = new domainManager.DomainManager()16 domains.scanDomains(domainsDirectory)17 domains.domains.should.eql([18 {19 domain: 'localhost',20 path: path.join(domainsDirectory, 'localhost')21 },22 {23 domain: 'testdomain.com',24 path: path.join(domainsDirectory, 'testdomain.com')25 }26 ])27 })28 })29 it('should ignore any files and only include directories', () => {30 const domainsDirectory = path.resolve(config.get('multiDomain.directory'))31 const mockFile1 = path.join(domainsDirectory, 'not-a-domain')32 const mockFile2 = path.join(33 domainsDirectory,34 'definitely-not-a-domain.js'35 )36 return Promise.all([fs.ensureFile(mockFile1), fs.ensureFile(mockFile2)])37 .then(() => {38 const domains = new domainManager.DomainManager()39 domains.scanDomains(domainsDirectory)40 should.not.exist(41 domains.domains.find(item => {42 return ['not-a-domain', 'definitely-not-a-domain.js'].includes(43 item.domain44 )45 })46 )47 return fs.remove(mockFile1)48 })49 .then(() => {50 return fs.remove(mockFile2)51 })52 })53 })54 describe('`addDomain()` method', () => {55 it('should add the specified domain to the internal map of domains', () => {56 const domains = new domainManager.DomainManager()57 domains.addDomain('test-domain', {})58 domains.getDomain('test-domain').should.eql({domain: 'test-domain'})59 })60 })61 describe('`removeDomain()` method', () => {62 it('should remove the specified domain from the internal map of domains', () => {63 const domains = new domainManager.DomainManager()64 domains.removeDomain('test-domain')65 const domain = domains.getDomain('test-domain')66 ;(typeof domain).should.eql('undefined')67 })68 })69 describe('`getDomains()` method', () => {70 it('should return the full array of domains and paths', () => {71 const domainsDirectory = path.resolve(config.get('multiDomain.directory'))72 return Promise.all([73 fs.ensureDir(path.join(domainsDirectory, 'localhost')),74 fs.ensureDir(path.join(domainsDirectory, 'testdomain.com'))75 ]).then(() => {76 const domains = new domainManager.DomainManager()77 domains.scanDomains(domainsDirectory)78 domains.getDomains().should.eql(domains.domains)79 })80 })81 })82 describe('`getDomain()` method', () => {83 it('should return the name and path of a matching domain', () => {84 const domainsDirectory = path.resolve(config.get('multiDomain.directory'))85 return Promise.all([86 fs.ensureDir(path.join(domainsDirectory, 'localhost')),87 fs.ensureDir(path.join(domainsDirectory, 'testdomain.com'))88 ]).then(() => {89 const domains = new domainManager.DomainManager()90 domains.scanDomains(domainsDirectory)91 domains.getDomain('localhost').should.eql(domains.domains[0])92 domains.getDomain('testdomain.com').should.eql(domains.domains[1])93 })94 })95 it('should return `undefined` when given a domain that is not configured', () => {96 const domainsDirectory = path.resolve(config.get('multiDomain.directory'))97 const domains = new domainManager.DomainManager()98 domains.scanDomains(domainsDirectory)99 should.not.exist(domains.getDomain('lolcathost'))100 })101 })...
grab-pages-responses.js
Source:grab-pages-responses.js
...16const pagesPath = path.join(responsesPath, 'getPage');17const layoutsPath = path.join(responsesPath, 'getLayout');18(async () => {19 await fs.remove(pagesPath);20 await fs.ensureDir(pagesPath);21 await fs.remove(layoutsPath);22 await fs.ensureDir(layoutsPath);23 console.log(`Getting main page global data from ${baseUrl}...\n`);24 let globalPageData = await request(util.format(pagesDataEndpoints.global, 'home'));25 globalPageData = JSON.parse(globalPageData.body);26 const links = globalPageData.data.global.links;27 await fs.ensureDir(responsesPath);28 await fs.ensureDir(pagesPath);29 await fs.ensureDir(layoutsPath);30 const responseDescriptor = {31 "request": {32 "queryParameters": {},33 "method": "get",34 "headers": {},35 "body": {}36 },37 "response": {38 "dataPath": "data.json",39 "statusCode": "200",40 "headers": {41 "content-type": "application/json"42 }43 }44 };45 for(linkKey in links) {46 const linkObject = links[linkKey];47 const pagePath = path.join(pagesPath, linkObject.pageType, linkObject.repositoryId);48 const layoutPath = path.join(layoutsPath, linkObject.pageType, linkObject.repositoryId);49 await fs.ensureDir(pagePath);50 await fs.ensureDir(layoutPath);51 for(pageDataType in pagesDataEndpoints) {52 const currentPath = pageDataType === 'layout' ? layoutPath : pagePath;53 const normalizedRoute = linkObject.route.replace(/^\/{1}/, '');54 const dataTypeEndpoint = util.format(pagesDataEndpoints[pageDataType], normalizedRoute);55 const dataTypePath = path.join(currentPath, pageDataType);56 const dataTypeQueryParameters = url.parse(dataTypeEndpoint, true).query;57 await fs.ensureDir(dataTypePath);58 console.log(`Getting data from ${util.format(dataTypeEndpoint, dataTypeEndpoint)}...`);59 const routeResponse = await request(util.format(dataTypeEndpoint, dataTypeEndpoint));60 const parseBody = JSON.parse(routeResponse.body);61 // Don't keep any widgets, we are going to mock this62 if(parseBody.hasOwnProperty('regions')) {63 parseBody.regions.forEach(region => {64 region.widgets = [];65 });66 }67 // Don't keep information about resolution on layouts, it will force us to generate one layout for each resolution68 // we should mock this when necessary69 if(pageDataType === 'layout' && dataTypeQueryParameters['ccvp']) {70 delete dataTypeQueryParameters['ccvp'];71 }...
render.js
Source:render.js
...15} from './consts/categories';16import getFilesizeInMegaBytes from './services/fileSize/index';17function renderPage(url: string, pagePath: string): Promise<boolean | Error> {18 return new Promise((resolve, reject) => {19 fs.ensureDir(pagePath).then(() => {20 const filePath = path.relative(process.cwd(), path.join(pagePath, 'index.html'));21 let htmlStream;22 try {23 htmlStream = markup(url);24 } catch (err) {25 console.error(err);26 process.exit(1); // ideally should be reject, but careful that return code is still 1 of the script27 }28 if (htmlStream) {29 const fileStream = fs.createWriteStream(filePath);30 htmlStream.pipe(fileStream);31 fileStream.on('close', () => {32 console.log(33 `[render] â ${getFilesizeInMegaBytes(filePath)} ${filePath.replace(34 url,35 `${colors.blue(url)}`,36 )}`,37 );38 resolve(true);39 });40 fileStream.on('error', err => {41 console.error(`[render] Error: ${err}`);42 reject(err);43 });44 }45 });46 });47}48async function render() {49 const rootDir = path.join(__dirname, '../static');50 // const outputDir = path.join(rootDir, 'pages');51 await fs.ensureDir(rootDir);52 // await fs.ensureDir(outputDir);53 // TODO: try catch54 await renderPage(`/`, rootDir); // put main index.html to static55 const aboutDir = path.join(rootDir, 'about');56 await fs.ensureDir(aboutDir);57 await renderPage(`/about/`, aboutDir);58 const companiesDir = path.join(rootDir, 'companies-hiring-remotely');59 await fs.ensureDir(companiesDir);60 await renderPage(`/companies-hiring-remotely/`, companiesDir);61 await Object.keys(CATEGORIES).reduce(async (pacc, category) => {62 return pacc.then(async () => {63 const filepath = path.join(rootDir, `remote-${category}-jobs`);64 await fs.ensureDir(filepath);65 await renderPage(`/remote-${category}-jobs/`, filepath);66 });67 }, Promise.resolve());68 await Object.keys(DEV_CATEGORIES).reduce(async (pacc, category) => {69 return pacc.then(async () => {70 console.log(`[render] ${category}`);71 const filepath = path.join(72 rootDir,73 DEV_CATEGORIES_META[category].link.slice(1, DEV_CATEGORIES_META[category].link.length - 1),74 );75 await fs.ensureDir(filepath);76 await renderPage(DEV_CATEGORIES_META[category].link, filepath);77 });78 }, Promise.resolve());79 await Object.keys(SUBSUBCATEGORIES).reduce(async (pacc, category) => {80 return pacc.then(async () => {81 console.log(`[render] ${category}`);82 const filepath = path.join(83 rootDir,84 SUBSUBCATEGORIES_META[category].link.slice(85 1,86 SUBSUBCATEGORIES_META[category].link.length - 1,87 ),88 );89 await fs.ensureDir(filepath);90 await renderPage(SUBSUBCATEGORIES_META[category].link, filepath);91 });92 }, Promise.resolve());93 console.log('[render] done');94}...
index.ts
Source:index.ts
...13 const project = {14 title: appName15 }16 console.log(`Creating ${project.title}`)17 let rootDir = await fs.ensureDir(`${process.cwd()}/${project.title}`);18 await fs.outputFile(`${rootDir}/package.json`, JSON.stringify(createPackageJson(project.title)));19 //create the src directory and index.html and reset.css file20 let srcDir = await fs.ensureDir(`${process.cwd()}/${project.title}/src`);21 await fs.outputFile(`${srcDir}/index.html`, createHTML(project.title));22 await fs.outputFile(`${srcDir}/reset.scss`, resetCSS());23 //create the app directory24 let appDir = await fs.ensureDir(`${srcDir}/app`)25 let apiDir = await fs.ensureDir(`${srcDir}/API`)26 await fs.outputFile(`${apiDir}/get.js`, createAPIGet());27 await fs.outputFile(`${apiDir}/post.js`, createAPIPost());28 await fs.outputFile(`${apiDir}/put.js`, createAPIPut());29 await fs.outputFile(`${apiDir}/deleteOne.js`, createAPIDeleteOne());30 let componentDir = await fs.ensureDir(`${appDir}/components`);31 let stylesDir = await fs.ensureDir(`${appDir}/styles`);32 await fs.outputFile(`${appDir}/index.jsx`, reactIndex(project.title));33 await fs.outputFile(`${appDir}/index.scss`, createReactSCSS());34 await shell.cd(project.title);35 for (const dependency of dependencies) {36 await shell.exec(`npm i ${dependency}`)37 }38 for (const dependency of devDependencies) {39 await shell.exec(`npm i -D ${dependency}`)40 }41};42createFile()...
utils.js
Source:utils.js
...21 "tenantId":9,22 "image":""23 }24 };25 fs.ensureDir(`${configDir}/easemob`, function(err){26 console.log(err);27 });28 fs.ensureDir(`${configDir}/easemob-desktop`, function(err){29 console.log(err);30 });31 // 头åæ件夹ä¸å建ä¸ä¸ªç¨æ·æ件夹ï¼ä¸åçç¨æ·å¤´ååæ¾å¨ä¸åçæ件夹ä¸32 // å建ä¸ä¸ªæ件夹ç¨æ¥åæ¾å¤´å33 fs.ensureDir(`${configDir}/easemob/easemobAvatar`, function(err){34 console.log(err);35 });36 fs.ensureDir(`${configDir}/easemob/easemobAvatar/user`, function(err){37 console.log(err);38 });39 // å建ä¸ä¸ªæ件夹ç¨æ¥åæ¾ pasteImage40 fs.ensureDir(`${configDir}/easemob/pasteImage`, function(err){41 console.log(err);42 });43 this.chatConfigs = new easemob.EMChatConfig(`${configDir}/easemob-desktop`, `${configDir}/easemob-desktop`, (userInfo && userInfo.user.appkey), 0);44 this.chatConfigs.setDeleteMessageAsExitGroup(true);4546 const emclient = new easemob.EMClient(this.chatConfigs);47 return emclient;48 }49};505152export default{53 utils54};
ejectBuild.js
Source:ejectBuild.js
...14} = {}) => {15 const corePath = `${engineRoot}/${projectType}`;16 progress(`Unlink ${Path.basename(outputRoot)}`);17 await rmdir(outputRoot);18 await fs.ensureDir(outputRoot);19 progress("Copy core");20 await copy(corePath, outputRoot);21 await fs.ensureDir(`${outputRoot}/src/data`);22 await fs.ensureDir(`${outputRoot}/node_modules`);23 await fs.ensureDir(`${outputRoot}/obj`);24 await fs.ensureDir(`${outputRoot}/obj/music`);25 await fs.ensureDir(`${outputRoot}/obj/data`);26 await fs.ensureDir(`${outputRoot}/build/rom`);27 for (const filename in compiledData.files) {28 if (filename.endsWith(".h")) {29 progress(`Copy header ${filename}`);30 await fs.writeFile(31 `${outputRoot}/include/${filename}`,32 compiledData.files[filename]33 );34 } else {35 progress(`Copy code ${filename}`);36 await fs.writeFile(37 `${outputRoot}/src/data/${filename}`,38 compiledData.files[filename]39 );40 }...
Using AI Code Generation
1describe('Test', () => {2 it('Test', () => {3 cy.writeFile('cypress/fixtures/test.json', 'test content');4 cy.readFile('cypress/fixtures/test.json').then((content) => {5 cy.ensureDir('cypress/fixtures/testDir');6 cy.writeFile('cypress/fixtures/testDir/test.json', content);7 });8 });9});
Using AI Code Generation
1const fs = require('fs-extra')2fs.ensureDir('cypress/screenshots')3const fs = require('fs-extra')4fs.ensureDir('cypress/videos')5const fs = require('fs-extra')6fs.ensureDir('cypress/fixtures')7const fs = require('fs-extra')8fs.ensureDir('cypress/support')9const fs = require('fs-extra')10fs.ensureDir('cypress/integration')11const fs = require('fs-extra')12fs.ensureDir('cypress/plugins')13const fs = require('fs-extra')14fs.ensureDir('cypress/support/commands')15const fs = require('fs-extra')16fs.ensureDir('cypress/support/index.js')17const fs = require('fs-extra')18fs.ensureDir('cypress/plugins/index.js')19const fs = require('fs-extra')20fs.ensureDir('cypress/support/commands.js')21const fs = require('fs-extra')22fs.ensureDir('cypress/support/commands.js')
Using AI Code Generation
1fs.ensureDir('cypress/screenshots', () => {2})3const fs = require('fs-extra')4module.exports = (on, config) => {5 fs.ensureDir('cypress/screenshots', () => {6 })7}8const fs = require('fs-extra')9fs.ensureDir('cypress/screenshots', () => {10})11const fs = require('fs-extra')12Cypress.Commands.add('ensureDir', () => {13 fs.ensureDir('cypress/screenshots', () => {
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.
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.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!