Best JavaScript code snippet using cypress
sitecheck.js
Source:sitecheck.js
1import AbstructProcess from "./abstruct_process.js"2import cheerio from 'cheerio'3import request from 'request'4import fsextra from "fs-extra"5import htmllint from "htmllint"6import htmllintMessageJa from "../misc/htmllint_message_ja.js"7import config from "../config.js"8import exportCsv from "../misc/export_csv.js"9import Queue from "../queue"10import {log} from "../misc/util.js"11const options = config.get("sitecheck")12// htmllint ã®ã«ã¼ã«ãå®ç¾©13// https://github.com/htmllint/htmllint/wiki/Options14htmllint.rules = options.htmllintRules15export default class SiteCheck extends AbstructProcess {16 /**17 * @param pages ãã§ãã¯ãããã¼ã¸ä¸è¦§18 */19 constructor(pages) {20 super()21 // ãã§ãã¯ãããã¼ã¸22 if (typeof pages === "undefined") {23 throw new Error("Invaild Paramater. Required Page List.")24 }25 this.queue = new Queue(pages.reverse())26 this.data = [];27 this.data.push(this.getHeaders());28 this.run()29 return this30 }31 /**32 * CSVã®ãããã¼ãè¿ã33 * @returns {[string,string,string,string,string,string,string,string]}34 */35 getHeaders() {36 return ["id", "url", "title", "description", "h1", "h2", "tel&fax", "tel link", "html lint"]37 }38 /**39 * Arrayãæ¡å¼µãããªãã¸ã§ã¯ããæºåãã40 * @returns {Array}41 */42 getDefaultRowArray() {43 var row = [];44 row.__proto__.pushData = function (selector, defaults, callback) {45 this.push(SiteCheck.parse(selector, defaults, callback))46 }47 return row;48 }49 /**50 * URLããrequestãéä¿¡ãã51 * 調æ»é
ç®ã data ããããã£ã¸ä¿ç®¡ãã52 *53 * @returns {boolean}54 */55 run() {56 if (!this.queue.isNext()) {57 this.output(this.data)58 return false;59 }60 var checkurl = this.queue.next()61 /**62 * URLãåå¾63 */64 request(checkurl, (error, response, body) => {65 let row = this.getDefaultRowArray()66 let $ = cheerio.load(body)67 row.push(this.data.length)68 row.push(checkurl)69 // ã¿ã¤ãã«70 row.pushData($("title"), "ã¿ã¤ãã«ãè¨å®ããã¦ãã¾ãã")71 // 説ææ72 row.pushData($("meta[name='description']"), "説ææãè¨å®ããã¦ãã¾ãã", (data) => {73 return data.attr("content")74 })75 // h176 row.pushData($("h1"), "h1ãè¨å®ããã¦ãã¾ãã", (data) => {77 if (data.find("img").length) {78 return data.find("img").attr("alt");79 }80 return data.text().replace(/\r?\n/g, "").trim();81 })82 // h283 row.pushData($("h2"), "h2ãè¨å®ããã¦ãã¾ãã", (data) => {84 return data.text().replace(/\r?\n/g, "").trim()85 })86 // tel87 row.pushData(body, "é»è©±çªå·ãããã¾ãã", (data) => {88 var telMatch = data.match(/0\d{1,3}-\d{2,4}-\d{4}/g)89 if (telMatch && telMatch.length >= 1) {90 return telMatch.join(",")91 }92 })93 // é»è©±çªå·ãªã³ã¯94 row.pushData($("a[href^='tel:']"), "é»è©±çªå·ãªã³ã¯ã¯è¦ã¤ããã¾ããã§ãã", (telLinks) => {95 var tellinkstext = "ãªã"96 if (telLinks && telLinks.length >= 1 && typeof telLinks.join !== "undefined") {97 tellinkstext = telLinks.join("\,")98 }99 return tellinkstext;100 })101 htmllint(body).then((issues) => {102 var _issues = []103 issues.forEach((issue) => {104 var msg = [105 'line ', issue.line, ', ',106 'col ', issue.column, ', ',107 htmllintMessageJa.renderIssue(issue)108 ].join('');109 _issues.push(msg);110 });111 var parsemsg = _issues.join('\n');112 row.push(parsemsg.replace(/"/g, '\"'))113 })114 this.data.push(row);115 this.run();116 })117 }118 /**119 * ãã¼ã¿ãCSVã§åºå120 * @param data121 */122 output() {123 var lineArray = []124 var headers = this.data[0]125 this.data.forEach(function (infoArray, index) {126 var obj = {}127 for (var i = 0; i < headers.length; i++) {128 obj[headers[i]] = infoArray[i]129 }130 lineArray.push(obj)131 })132 exportCsv(lineArray).then((data) => {133 fsextra.outputFile(config.get("resultsDirPath") + options.output, data, (err, data) => {134 if (err) {135 throw new Error("CSVã¸ã®åºåã«å¤±æãã¾ãã")136 }137 this.resolve(this.data);138 })139 })140 }141 /**142 * chelio ãªãã¸ã§ã¯ããæ¡å¼µ143 *144 * @param selector145 * @param defaults146 * @param callback147 * @returns {*}148 */149 static parse(selector, defaults, callback) {150 var data = "";151 var parsecallback, defaultValue;152 if (typeof defaults === "function") {153 parsecallback = defaults;154 }155 if (typeof callback === "string") {156 defaultValue = callback;157 }158 if (typeof callback === "function") {159 parsecallback = callback160 }161 if (typeof defaultValue !== "undefined") {162 data = defaultValue;163 }164 var $selector = selector165 if (typeof parsecallback === "function") {166 data = parsecallback($selector);167 } else {168 if (typeof $selector.text === "function") {169 data = $selector.text().replace(/\r?\n/g, "").trim()170 }171 }172 if (typeof data === "undefined") {173 return "";174 }175 return data.replace(/(",)/g, "\\$1");176 }...
getlinks.js
Source:getlinks.js
1import AbstructProcess from "./abstruct_process.js"2import request from "request"3import cheerio from 'cheerio'4import URL from 'url-parse';5import fsextra from "fs-extra"6import config from "../config.js"7import exportCsv from "../misc/export_csv.js"8import Queue from "../queue"9import LinkQueue from "../queue/linkqueue.js"10const pages = config.get("pages")11const options = config.get("getlinks")12export default class GetLinks extends AbstructProcess {13 /**14 * @param startUrl åºç¹ã¨ãªãURL15 * @param limit å¶éæ°16 * @param ignoresPattern é¤å¤ããURLã®æ£è¦è¡¨ç¾ãã¿ã¼ã³17 */18 constructor(startUrl, limit, ignoresPattern) {19 super();20 this.linklist = new Queue();21 this.ignoresPattern = ignoresPattern22 this.startUrl = startUrl23 this.limit = limit24 this.countVisitedPage = 0;25 this.url = new URL(this.startUrl)26 this.baseUrl = this.url.protocol + "//" + this.url.hostname;27 this.queue = new LinkQueue();28 this.queue.add(this.startUrl);29 this.visitPage = this.visitPage.bind(this)30 this.crawl = this.crawl.bind(this)31 this.checkURL = this.checkURL.bind(this)32 this.crawl();33 }34 /**35 * URLãå·¡åãã36 */37 crawl() {38 var nextPage = this.queue.next();39 if (this.countVisitedPage >= this.limit || typeof nextPage === "undefined") {40 this.complete()41 return this.queue;42 }43 if (this.queue.find(nextPage) > 0) {44 this.crawl();45 } else {46 this.visitPage(nextPage, this.crawl);47 }48 }49 /**50 * ãã¼ã¸ãåå¾ãã51 */52 visitPage(url, callback) {53 this.countVisitedPage++;54 var self = this55 console.log(this.countVisitedPage +":" + url);56 request(url, function (error, response, body) {57 if (response.statusCode !== 200) {58 callback();59 return;60 }61 var $ = cheerio.load(body);62 self.linklist.add({url: url, title: $("title").text()})63 self.collectInternalLinks($);64 callback();65 });66 }67 /**68 * ãªã³ã¯ãããqueue ã¸æ ¼ç´ãã69 */70 collectInternalLinks($) {71 var relativeLinks = $("a[href^='/'],a[href^='http']");72 var self = this73 relativeLinks.each(function () {74 if (!self.checkURL($(this).attr('href'))) {75 return true;76 }77 if ($(this).attr('href').substr(0, 1) === "/") {78 self.queue.add(self.baseUrl + $(this).attr('href'));79 } else {80 if ($(this).attr('href').match(self.url.hostname)) {81 self.queue.add($(this).attr('href'));82 }83 }84 })85 }86 /**87 * ãã¼ã¯ã¼ããæ¤ç´¢ãã88 */89 searchForWord($, word) {90 var bodyText = $('html > body').text().toLowerCase();91 return (bodyText.indexOf(word.toLowerCase()) !== -1);92 }93 /**94 * URLããã§ãã¯ãã95 * @param url string96 */97 checkURL(url) {98 // é¤å¤ãã¿ã¼ã³ãã©ãã調æ»99 if (url.match(new RegExp(this.ignoresPattern, "g"))) {100 return false;101 }102 // ããã·ã¥ãã¾ãã¯ã¯ã¨ãªã¹ããªã³ã°ã§çæãããURLãç»åãã¡ã¤ã«æ¡å¼µåãå«ã¾ãªããã©ãã調æ»103 if (url.match(/(?:#|\?|\.png|\.jpg|\.jpeg|\.gif)/g)) {104 return false;105 }106 if (url[0] === "/") {107 var url = this.url.href + url;108 }109 // èªèº«ã®ãã¡ã¤ã³ã調æ»110 var _url = this.url.hostname.replace(/[\-|\.|\_]/g, function (match) {111 return "\\" + match;112 })113 var reg = new RegExp("^https?:\/\/" + _url + ".*?[^?].*", "g")114 var match = url.match(reg)115 return !( match == null )116 }117 /**118 * CSVã«åºåãã119 */120 output() {121 this.linklist.sort("url");122 var lineArray = []123 var headers = ["ID", "url", "title"]124 lineArray.push(headers)125 this.linklist.forEach(function (infoArray, index) {126 var _infoArray = [index+1, infoArray.url, infoArray.title]127 lineArray.push(_infoArray)128 })129 exportCsv(lineArray).then((data) => {130 fsextra.outputFile(config.get("resultsDirPath") + options.output, data, (err, data) => {131 if (err) {132 throw new Error("ãã¡ã¤ã«ã®åºåã«å¤±æãã¾ãã")133 }134 })135 })136 }137 /**138 * å®äºæã®å¦ç139 */140 complete(){141 this._resolve(this.linklist.all());142 this.output()143 }...
ViewRenderingService.js
Source:ViewRenderingService.js
1// api/services/ViewRenderingService.js2var fs = require("fs");3var fsextra = require('fs-extra');4module.exports = {5 /**6 * Send a customized welcome email to the specified email address.7 *8 * @required {String} emailAddress9 * The email address of the recipient.10 * @required {String} firstName11 * The first name of the recipient.12 */13 //-----------------------------------------------14 // NOTES15 // Inorder to make this work we need to disable layout in config/view.js16 // otherwise it expects layout.ejs in the respective folder17 // REFERENCES18 //http://stackoverflow.com/questions/24187206/how-to-render-a-view-into-a-string-in-sailsjs19 //https://github.com/balderdashy/sails/issues/245920 render: function (options) {21 sails.hooks.views.render(22 options.template,23 options.data,24 function (err, view) {25 if (err) {26 throw err;27 } else {28 //sails.log.debug("view =>" + view);29 fsextra.outputFile(options.savetofolder, view, function (err) {30 if (err) throw err;31 });32 return view;33 }34 }35 );36 },37 scaffold: function (options) {38 try {39 sails.log.info("Inside code generation");40 for (i = 0; i < options.template.length; i++) {41 //sails.log("options.template[i]=" + options.template[i])42 sails.hooks.views.render(43 options.template[i],44 options.data,45 function (err, view) {46 if (err) {47 throw err;48 } else {49 var EntityName = sails._s.capitalize(options.data.table);50 var fileName = (options.template[i].split("/").pop() + '.vue').replace("Entity",EntityName)51 fsextra.outputFile(options.savetofolder + EntityName.toLowerCase() + "/" + fileName, view, function (err) {52 if (err) throw err;53 });54 return view;55 }56 }57 );58 }59 } catch (e) {60 sails.log.error(e);61 }62 },...
word.js
Source:word.js
1//var pdfDocService = require('../../services/DcoumentExportService');2var fsextra = require('fs-extra');3module.exports = {4 5 friendlyName: 'Word',6 description: 'For a given docx template and data, generates word files and sends it back as byte stream ',7 inputs: {8 template:{9 type: 'string',10 required: true11 },12 data:{13 type: 'json'14 },15 filename:{16 type: 'string',17 required: true18 }19 },20 exits: {21 success: {22 description: 'Word file has been generated successfully',23 responseType: 'ok'24 }25 },26 fn: async function (inputs,exits) {27 sails.log(inputs)28 const createReport = require('docx-templates').default;29 const fs = require('fs')30 sails.log(sails.config.settings.templates.word.path + inputs.template)31 const template = fs.readFileSync(sails.config.settings.templates.word.path + inputs.template);32 const buffer = await createReport({33 template,34 data: inputs.data,35 });36 //create report & store it in temp folder37 //fs.writeFileSync('.code/senthil_invoice.docx', buffer)38 sails.log(sails.config.settings.data.temp.path + inputs.filename)39 //fs.writeFileSync(sails.config.settings.data.temp.path + inputs.filename, buffer)40 fsextra.outputFile(sails.config.settings.data.temp.path + inputs.filename, buffer, function (err) {41 if (err) throw err;42 });43 //Convert to pdf44 //pdfDocService.ConvertDocToPdf('.code/2.docx','.code/senthil_invoice.pdf');45 //Send the reponse to client46 this.res.attachment(inputs.filename);47 const { Readable } = require('stream');48 var stream = new Readable();49 stream.push(buffer);50 stream.push(null);51 return stream.pipe(this.res);52 }...
build.js
Source:build.js
1const sass = require('node-sass');2const fsextra = require('fs-extra');3const sources = [4 './seedlings-marketing.scss',5];6const BANNER = ` /*7 /$$$$$$ /$$ /$$ /$$8 /$$__ $$ | $$| $$|__/9| $$ \\__/ /$$$$$$ /$$$$$$ /$$$$$$$| $$ /$$ /$$$$$$$ /$$$$$$ /$$$$$$$10| $$$$$$ /$$__ $$ /$$__ $$ /$$__ $$| $$| $$| $$__ $$ /$$__ $$ /$$_____/11 \\____ $$| $$$$$$$$| $$$$$$$$| $$ | $$| $$| $$| $$ \\ $$| $$ \\ $$| $$$$$$12 /$$ \\ $$| $$_____/| $$_____/| $$ | $$| $$| $$| $$ | $$| $$ | $$ \\____ $$13| $$$$$$/| $$$$$$$| $$$$$$$| $$$$$$$| $$| $$| $$ | $$| $$$$$$$ /$$$$$$$/14 \\______/ \\_______/ \\_______/ \\_______/|__/|__/|__/ |__/ \\____ $$|_______/15 /$$ \\ $$16 | $$$$$$/17 \\______/18https://github.com/sproutsocial/seeds-packets/tree/main/packets/seedlings19*/20`;21sources.forEach(source => {22 sass.render(23 {24 file: source,25 outFile: `./dist/${source}`,26 includePaths: ['node_modules']27 },28 (err, result) => {29 if (err) {30 throw err;31 }32 const data = `${BANNER} \n ${result.css}`;33 fsextra.outputFile(`./dist/${source.replace('scss', 'css')}`, data, err => {34 if (err) {35 throw err;36 } else {37 console.info(`âï¸ dist/${source.replace('./', '').replace('scss', 'css')}`);38 }39 });40 }41 );...
Using AI Code Generation
1describe('Test', () => {2 it('should write to file', () => {3 cy.writeFile('cypress/fixtures/example.json', { name: 'John Doe' })4 })5})6{7}
Using AI Code Generation
1const fs = require('fs-extra')2const path = require('path')3const filePath = path.resolve(__dirname, 'test.txt')4fs.outputFile(filePath, fileContent, 'utf8', (err) => {5 if (err) return console.error(err)6 console.log('File created!')7})8describe('Test', () => {9 it('should create a file', () => {10 cy.exec('node test.js')11 })12})13const fs = require('fs-extra')14describe('Test', () => {15 it('should create a file', () => {16 fs.outputFile('test.txt', 'Hello world!', 'utf8', (err) => {17 if (err) return console.error(err)18 console.log('File created!')19 })20 })21})22const fs = require('cypress-fs')23describe('Test', () => {24 it('should create a file', () => {25 fs.outputFile('test.txt', 'Hello world!', 'utf8', (err) => {26 if (err) return console.error(err)27 console.log('File created!')28 })29 })30})
Using AI Code Generation
1const fsExtra = require('fs-extra')2const path = require('path')3const fixturePath = path.join(__dirname, '..', 'fixtures', 'test.json')4fsExtra.outputFile(fixturePath, JSON.stringify({ name: 'test' }))5describe('Test', () => {6 it('should work', () => {7 cy.fixture('test').should('deep.equal', { name: 'test' })8 })9})
Using AI Code Generation
1const fsExtra = require("fs-extra");2const path = require("path");3const fileName = "test.json";4const filePath = path.join(__dirname, "../fixtures", fileName);5const data = {6};7fsExtra.outputFile(filePath, JSON.stringify(data, null, 2), (err) => {8 if (err) {9 return console.log(err);10 }11 console.log("Success!");12});13describe("Test", () => {14 it("should write file to fixtures folder", () => {15 cy.writeFile("test.json", { name: "John Doe", age: 34 });16 });17});18describe("Test", () => {19 it("should write file to fixtures folder", () => {20 cy.writeFile("test.json", { name: "John Doe", age: 34 });21 cy.readFile("@test").should("deep.equal", { name: "John Doe", age: 34 });22 });23});
Using AI Code Generation
1const fsExtra = require('fs-extra')2const path = require('path')3const filePath = path.resolve('cypress/fixtures', 'myFile.json')4fsExtra.outputFile(filePath, 'Hello World!')5 .then(() => {6 console.log('success!')7 })8 .catch(err => {9 console.error(err)10 })11const fsExtra = require('fs-extra')12const path = require('path')13const filePath = path.resolve('cypress/fixtures', 'myFile.json')14fsExtra.outputFile(filePath, 'Hello World!')15 .then(() => {16 console.log('success!')17 })18 .catch(err => {19 console.error(err)20 })21const fsExtra = require('fs-extra')22const path = require('path')23const filePath = path.resolve('cypress/fixtures', 'myFile.json')24fsExtra.outputFile(filePath, 'Hello World!')25 .then(() => {26 console.log('success!')27 })28 .catch(err => {29 console.error(err)30 })31const fsExtra = require('fs-extra')32const path = require('path')33const filePath = path.resolve('cypress/fixtures', 'myFile.json')34fsExtra.outputFile(filePath, 'Hello World!')35 .then(() => {36 console.log('success!')37 })38 .catch(err => {39 console.error(err)40 })41const fsExtra = require('fs-extra')42const path = require('path')43const filePath = path.resolve('cypress/fixtures', 'myFile.json')44fsExtra.outputFile(filePath, 'Hello World!')45 .then(() => {46 console.log('success!')47 })48 .catch(err => {
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!!