Best JavaScript code snippet using nightwatch
index.js
Source:index.js
1//requires2const axios = require('axios');3const fs = require('fs');4//get app credentials from file5const {client_id, secret} = require('./auth.json');6//set required cmd line args7let argv = require('yargs/yargs')(process.argv.slice(2))8 .usage('Usage: $0 --guildID [numeric guild id] --guildTagID [numeric tag ID] --startTime [unix timestamp] --webhook [url]')9 .demandOption(['guildID','guildTagID', 'startTime', 'webhook'])10 .argv;11//init vars12let bearerToken;13let fileName = './processedReports';14let logTimestamp = new Date();15//touch processed file16fs.closeSync(fs.openSync(fileName, 'a'));17//get bearer token18const getToken = () => {19 try {20 return axios.post('https://www.warcraftlogs.com/oauth/token', {21 grant_type: 'client_credentials'22 },23 {24 auth: {25 password: secret,26 username: client_id27 }28 })29 } catch (error) {30 console.error(logTimestamp.toLocaleString(), error.message);31 }32};33//set bearer token to var34const setToken = async () => {35 await getToken()36 .then(response => {37 bearerToken = response.data.access_token;38 })39 .catch(error => {40 console.error(logTimestamp.toLocaleString(), error.message)41 });42};43//continue to fetch reports after setting token44setToken().then(function () {45 fetchList();46});47//fetch reports48async function fetchList () {49 await axios({50 url: "https://www.warcraftlogs.com/api/v2/client",51 method: 'post',52 headers: {53 'Content-Type': 'application/json',54 'Authorization': `Bearer ${bearerToken}`55 },56 data: {57 query: `query {58 reportData {59 reports (60 limit: 561 guildID: ${argv.guildID}62 guildTagID: ${argv.guildTagID}63 startTime: ${argv.startTime}64 ) {65 data {66 code67 guildTag {68 name69 id70 }71 startTime72 endTime73 title74 zone {75 name76 }77 owner {78 name79 }80 }81 }82 }83 }84 `85 }86 }).then(response => {87 let results = response.data.data.reportData.reports;88 //iterate through results89 for (let report in results.data) postToDiscord(results.data[report]);90 }).catch(error => {91 console.error(logTimestamp.toLocaleString(), error.message);92 })93}94//send notification to Discord webhook95function postToDiscord (reportData) {96 //format timestamp to make Discord happy97 let timestamp = new Date(reportData.startTime);98 //check the report code and see if we've already sent this one99 fs.readFile(fileName, function (err, data) {100 if (err) throw err;101 if(data.includes(reportData.code)){102 //exit function if exists103 console.log(reportData.code, " already sent!");104 return false;105 }106 else if (!reportData.zone) {107 console.log(reportData.code, " is missing zone information, not sent!");108 return false;109 }110 else {111 //post to Discord112 console.log(JSON.stringify(reportData));113 axios.post(argv.webhook,{114 "content": "New WCL upload",115 "embeds": [116 {117 "title": reportData.title,118 "description": reportData.guildTag.name + " - " + reportData.zone.name,119 "url": "https://www.warcraftlogs.com/reports/" + reportData.code,120 "timestamp": timestamp.toISOString(),121 "footer": {122 "text": "Uploaded by " + reportData.owner.name123 }124 }125 ]126 }).then(()=> {127 //write to file128 fs.appendFileSync(fileName, `${logTimestamp.toLocaleString()} - ${reportData.code} - ${reportData.guildTag.name}\n`)129 }).catch(error => console.error(logTimestamp.toLocaleString(), error.message))130 }131 });...
logs.js
Source:logs.js
1import moment from 'moment';2import Log from './model';3import send from '../../apiTools/send';4export default {5 /**6 * Allows you to pass a data object which is recorded as a log entry.7 * @param data8 * @returns {Promise}9 */10 writeLog(data) {11 const logData = data;12 logData.logTimestamp = moment().format();13 logData.logCode = data.logCode.toUpperCase();14 return new Promise((resolve, reject) => {15 const log = new Log(logData);16 console.info(logData);17 log.save()18 .then(result => resolve(send.set200(result, 'Log')))19 .catch((error) => {20 console.error(error);21 return reject(send.fail500(error))22 });23 });24 },25 /**26 * returns all logs from the DB27 * @returns {Promise}28 */29 getLogs() {30 return new Promise((resolve, reject) => {31 Log.find({})32 .then(result => resolve(send.set200(result, 'Log')))33 .catch((err) => {34 console.error(err);35 return reject(send.fail500(err));36 });37 });38 },39 /**40 * Return all logs of a single code: ERROR, NOTIFY, SUCCESS41 * @param code42 * @returns {Promise}43 */44 getLogByCode(code) {45 return new Promise((resolve, reject) => {46 Log.find({ logCode: code })47 .then(result => resolve(send.set200(result, 'Log')))48 .catch((err) => {49 console.error(err);50 return reject(send.fail500(err));51 });52 });53 },54 /**55 * Return a single log with code and timestamp56 * @param code57 * @param timestamp58 * @returns {Promise}59 */60 getLog(code, timestamp) {61 return new Promise((resolve, reject) => {62 Log.findOne({ logCode: code, logTimestamp: timestamp })63 .then(result => resolve(send.set200(result, 'Log')))64 .catch((err) => {65 console.error(err);66 return reject(send.fail500(err));67 });68 });69 },70 /**71 * This method is async and does not return anything. It logs an error.72 * @param message73 */74 error(message) {75 const data = {76 logCode: 'ERROR',77 logTimestamp: moment().format(),78 message: `Caught Error at ${moment().format('LLLL')}. See details.`,79 details: message80 };81 const log = new Log(data);82 log.save()83 .then(result => console.info(result))84 .catch(error => console.error(error));85 },86 /**87 * This method is async and does not return anything.88 * It records a notification message in the log.89 * @param message90 */91 notify(message) {92 const data = {93 logCode: 'NOTIFY',94 logTimestamp: moment().format(),95 message96 };97 const log = new Log(data);98 log.save()99 .then(result => console.info(result))100 .catch(error => console.error(error));101 },102 /**103 * This method is async and does not return anything. It logs a success message.104 * @param message105 */106 success(message) {107 const data = {108 logCode: 'SUCCESS',109 logTimestamp: moment().format(),110 message111 };112 const log = new Log(data);113 log.save()114 .then(result => console.info(result))115 .catch(error => console.error(error));116 },117 /**118 * This method is async and does not return anything.119 * It logs your choice of ERROR, NOTIFY, or SUCCESS with details.120 * @param code121 * @param message122 * @param detail123 */124 detail(code, message, detail) {125 const data = {126 logCode: code,127 logTimestamp: moment().format(),128 message,129 details: detail130 };131 const log = new Log(data);132 log.save()133 .then(result => console.info(result))134 .catch(error => console.error(error));135 }...
Comment.js
Source:Comment.js
1import React, { useState, useEffect, Suspense, lazy } from "react";2import PropTypes from 'prop-types';3import { log, isAdmin } from '../common';4import { getComments, postComment } from './api';5import './Comment.css';6const CommentItem = lazy(() => import('./CommentItem'));7const CommentForm = lazy(() => import('./CommentForm'));8const Comment = (props) => {9 const [comments, setComments] = useState([]);10 const [buttonText, setButtonText] = useState("... comments");11 const [isShow, setIsShow] = useState(false);12 const [isOpenReplyForm, setIsOpenReplyForm] = useState(false);13 const logTimestamp = props.logTimestamp;14 const fetchData = async(timestamp) => {15 const admin = isAdmin();16 // Call GET API17 try {18 const res = await getComments(timestamp, admin);19 const newData = await res.json();20 // Sort by sortKey21 newData.body.Items.sort((a, b) => {22 return (a.sortKey < b.sortKey) ? -1 : 123 });24 log("Comments are FETCHED successfully.");25 const count = newData.body.Items.length;26 27 // Set comment button text28 1 < count ? setButtonText(count + " comments")29 : 1 === count ? setButtonText("1 comment")30 : setButtonText("Add a comment");31 // Set comment list32 setComments(newData.body.Items);33 }34 catch(err) {35 console.error(err);36 }37 }38 const newComment = async(comment) => {39 try {40 const res = await postComment(comment);41 if(200 === res.status) {42 log("A comment is POSTED successfully.");43 fetchData(comment.logTimestamp);44 }45 else {46 console.error(res);47 }48 }49 catch(err) {50 console.error(err);51 }52 }53 const openReplyForm = (isOpened) => {54 setIsOpenReplyForm(isOpened);55 }56 useEffect(() => fetchData(logTimestamp), [logTimestamp]);57 const toggleComments = () => setIsShow(!isShow)58 const commentThread = isShow59 ? (60 <div className="div div--comment-thread">61 <Suspense fallback={<div></div>}>62 {comments.map(data => ( 63 <CommentItem64 key={data.timestamp}65 isAdminComment={data.isAdminComment}66 message={data.message}67 name={data.name}68 logTimestamp={logTimestamp}69 commentTimestamp={data.commentTimestamp}70 timestamp={data.timestamp}71 isHidden={data.isHidden}72 openReplyForm={openReplyForm}73 reply={newComment}74 />75 ))}76 </Suspense>77 </div>78 )79 : "";80 const commentForm = isShow && !isOpenReplyForm81 ? <CommentForm82 logTimestamp={logTimestamp}83 post={newComment}84 />85 : "";86 const commentDivisionLine = isShow && !isOpenReplyForm ? <hr /> : "";87 return (88 <section className="section section--logitem-comment">89 <span90 className="span span--comment-togglebutton"91 onClick={toggleComments}92 >93 {buttonText}94 </span>95 {commentThread}96 {commentDivisionLine}97 {commentForm}98 </section>99 );100}101Comment.propTypes = {102 logTimestamp: PropTypes.number,103}...
logging.js
Source:logging.js
1import { app } from "electron";2import winston from "winston";3import path from "path";4const pad = (s, n) => {5 n = n || 2;6 s = Array(n).join("0") + s;7 return s.substring(s.length - n);8};9// logTimestamp is a function to format current time as a string using a10// format compatible to hcd/hcwallet logs. This function is meant to be11// installed in the winston loggers.12const logTimestamp = () => {13 let date = new Date();14 let y = date.getFullYear();15 let mo = pad(date.getMonth() + 1);16 let d = pad(date.getDate());17 let h = pad(date.getHours());18 let mi = pad(date.getMinutes());19 let s = pad(date.getSeconds());20 let ms = pad(date.getMilliseconds(), 3);21 return `${y}-${mo}-${d} ${h}:${mi}:${s}.${ms}`;22};23// logLevelsPrintable are the printable strings for each log level, compatible24// with the hcd/hcwallet logs.25const logLevelsPrintable = {26 "error": "ERR",27 "warn": "WRN",28 "info": "INF",29 "verbose": "VBS",30 "debug": "DBG",31 "silly": "TRC",32};33const logFormatter = (opts) => {34 //console.log(opts);35 const lvl = logLevelsPrintable[opts.level]||"UNK";36 const time = opts.timestamp();37 const msg = opts.message;38 const subsys = "HCI";39 return `${time} [${lvl}] ${subsys}: ${msg}`;40};41const logFormatterColorized = (opts) => {42 const config = winston.config;43 return config.colorize(opts.level, logFormatter(opts));44};45// createLogger creates the main app logger. This stores all logs into the46// hcgui app data dir and sends to the console when debug == true.47// This is meant to be called from the ipcMain thread.48export function createLogger(debug) {49 const logger = new (winston.Logger)({50 transports: [51 new (winston.transports.File)({52 json: false,53 filename: path.join(app.getPath("userData"), "hcGUI.log"),54 timestamp: logTimestamp,55 formatter: logFormatter,56 })57 ]58 });59 if (debug) {60 logger.add(winston.transports.Console, {61 timestamp: logTimestamp,62 formatter: logFormatterColorized,63 level: "debug",64 });65 }66 return logger;...
logger.js
Source:logger.js
1'use strict'2const path = require('path')3const fs = require('fs')4const winston = new require('winston')5const logPath = path.resolve(__dirname, 'logs')6try {7 fs.mkdirSync(logPath) 8}9catch (err) { 10}11const infoLogFile = path.resolve(logPath, 'info.log')12const warnLogFile = path.resolve(logPath, 'warn.log')13const errorLogFile = path.resolve(logPath, 'error.log')14const accessLogFile = path.resolve(logPath, 'access.log')15const logTimestamp = function() {16 return new Date().toISOString()17}18const logFormatter = function(options) {19 // - Return string will be passed to logger.20 // - Optionally, use options.colorize(options.level, <string>) to21 // colorize output based on the log level.22 return options.timestamp() + ' ' +23 config.colorize(options.level, options.level.toUpperCase()) + ' ' +24 (options.message ? options.message : '') +25 (options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' );26}27const config = winston.config;28const logger = new (winston.Logger)({29 transports: [30 new (winston.transports.Console)({31 timestamp: logTimestamp,32 formatter: logFormatter33 }),34 new (winston.transports.File)({ 35 name: 'infoLog',36 level: 'info',37 filename: infoLogFile,38 timestamp: logTimestamp,39 formatter: logFormatter40 }),41 new (winston.transports.File)({42 name: 'errorLog',43 level: 'error',44 filename: errorLogFile,45 timestamp: logTimestamp,46 formatter: logFormatter47 }),48 new (winston.transports.File)({49 name: 'accessLog',50 level: 'access',51 filename: accessLogFile,52 timestamp: logTimestamp,53 formatter: logFormatter54 })55 ]56})...
gameLog.js
Source:gameLog.js
1import fs from 'fs';2import path from 'path';3let logTimeStamp;4const getTimeStamp = () => {5 const currDate = new Date();6 const year = currDate.getFullYear();7 const month = currDate.getMonth();8 const day = currDate.getDay();9 const hours = currDate.getHours();10 const minutes = currDate.getMinutes();11 const seconds = currDate.getSeconds();12 return `${year}-${month}-${day}-${hours}-${minutes}-${seconds}`;13}14const logGameStart = (number, restart) => {15 if (logTimeStamp === undefined) {16 logTimeStamp = getTimeStamp();17 }18 const logFileName = path.join('./log', logTimeStamp + '.log');19 const currTimeStamp = getTimeStamp();20 const logContent = `${restart ? 'restart' : 'start'} number=${number} ${currTimeStamp}\n`;21 fs.appendFile(logFileName, logContent, (error) => {22 if (error) {23 console.log('writeFile error');24 }25 });26};27const logGuessNumber = (guessed) => {28 if (logTimeStamp === undefined) {29 logTimeStamp = getTimeStamp();30 }31 const logFileName = path.join('./log', logTimeStamp + '.log');32 const currTimeStamp = getTimeStamp();33 const logContent = `guess ${guessed} ${currTimeStamp}\n`;34 fs.appendFile(logFileName, logContent, (error) => {35 if (error) {36 console.log('writeFile error');37 }38 });39}40const logGameEnd = () => {41 if (logTimeStamp === undefined) {42 logTimeStamp = getTimeStamp();43 }44 const logFileName = path.join('./log', logTimeStamp + '.log');45 const logContent = `end-game\n`;46 fs.appendFile(logFileName, logContent, (error) => {47 if (error) {48 console.log('writeFile error');49 }50 });51}...
Log.js
Source:Log.js
1var crypt=require('crypto');2var mongojs=require("mongojs");3var q=require('q');4var config=require("../config");5var db=mongojs.mongojs(config.dburl,['Session','Packets','Messages']);6var sessionId=crypto.randomBytes(6).toString('base64');7var startTime=Date.now()/1000;8//don't care if index already exists mongo will just ignore the call9db.Session.createIndex({SessionId:1});10db.Packets.createIndex({SessionId:1});11db.Packets.createIndex({Timestamp:1});//used with the packets12db.Packets.createIndex({LogTimestamp:1});//used by the logger13db.Messages.createIndex({SessionId:1});14db.Messages.createIndex({LogTimestamp:1});15export.Message(msg){16 var defer=q.defer()17 var date=Date.now();18 db.Messages.save({19 TimeStamp:Date.now()/1000,20 Message:msg21 },function(err){22 if(err)23 defer.reject(err);24 else25 defer.resolve();26 });27 return defer.promise;28}29export.Packet(packet){30 var defer=q.defer()31 var date=Date.now()/1000;32 packet=packet.ROOT;33 packet.LogTimestamp=Date.now();34 packet.SessionId=sessionId;35 db.Packets.save({36 Timestamp:packet.Timestamp,37 LogTimestamp:date,38 'Length':packet.Length,39 SessionId:sessionId,40 Direction:packet.Direction,41 Frame:packet.Frame42 },function(err,doc){43 if(err)44 defer.reject(err);45 else46 defer.resolve(doc);47 });48 return defer.promise;49}50process.on('exit',function(){51 db.Session.Save({52 SessionId:sessionId,53 Start:startTime,54 End:Date.now()/100055 });56 process.exit();...
one-time-clicker.js
Source:one-time-clicker.js
1'use strict';2const button = document.querySelector('button');3let counter = 0;4function logTimestamp() {5 console.log(Date.now());6}7//Solution one8/*9button.addEventListener('click', logTimestamp);10button.addEventListener('click', function () {11 counter ++;12});13button.addEventListener('click', function () {14 if (counter > 0) {15 button.removeEventListener('click', logTimestamp);16 }17});18*/19//Solution two20button.addEventListener('click', function (e) {21 logTimestamp();22 e.target.disabled = true;...
Using AI Code Generation
1module.exports = {2 'Demo test Google' : function (browser) {3 .waitForElementVisible('body', 1000)4 .setValue('input[type=text]', 'nightwatch')5 .waitForElementVisible('button[name=btnG]', 1000)6 .click('button[name=btnG]')7 .pause(1000)8 .assert.containsText('#main', 'Night Watch')9 .end();10 }11};12{13 "selenium" : {14 "cli_args" : {15 }16 },17 "test_settings" : {18 "default" : {19 "screenshots" : {20 },21 "desiredCapabilities": {22 }23 },24 "chrome" : {25 "desiredCapabilities": {26 }27 }28 }29}30const seleniumServer = require('selenium-server');31const chromedriver = require('chromedriver');32const geckodriver = require('geckodriver');
Using AI Code Generation
1module.exports = {2 'Demo test Google' : function (browser) {3 .waitForElementVisible('body', 1000)4 .setValue('input[type=text]', 'nightwatch')5 .waitForElementVisible('button[name=btnG]', 1000)6 .click('button[name=btnG]')7 .pause(1000)8 .assert.containsText('#main', 'Night Watch')9 .end();10 }11};12module.exports = {13 selenium: {14 server_path: require('selenium-server').path,
Using AI Code Generation
1module.exports = {2 'Demo test Google': function (browser) {3 .waitForElementVisible('body', 1000)4 .setValue('input[type=text]', 'nightwatch')5 .waitForElementVisible('input[name=btnK]', 1000)6 .click('input[name=btnK]')7 .pause(1000)8 .assert.containsText('#main', 'Night Watch')9 .end();10 }11};12module.exports = {13 selenium: {
Using AI Code Generation
1module.exports = {2 'Demo test Google' : function (browser) {3 .waitForElementVisible('body', 1000)4 .logTimestamp('Google loaded')5 .setValue('input[type=text]', 'nightwatch')6 .waitForElementVisible('button[name=btnG]', 1000)7 .click('button[name=btnG]')8 .pause(1000)9 .logTimestamp('Nightwatch search complete')10 .end();11 }12};
Using AI Code Generation
1var logTimestamp = require('./logTimestamp.js');2module.exports = {3 'Demo test Google' : function (browser) {4 .waitForElementVisible('body', 1000)5 .setValue('input[type=text]', 'nightwatch')6 .waitForElementVisible('button[name=btnG]', 1000)7 .click('button[name=btnG]')8 .pause(1000)9 .assert.containsText('#main', 'Night Watch')10 .end();11 }12};13MIT © [Arthur Corenzan](
Using AI Code Generation
1module.exports = {2 'Test 1': function (browser) {3 .waitForElementVisible('body', 1000)4 .logTimestamp('Test 1')5 .end();6 }7};
Using AI Code Generation
1module.exports = {2 'Test 1': function (browser) {3 .logTimestamp('Test 1')4 .end();5 },6 'Test 2': function (browser) {7 .logTimestamp('Test 2')8 .end();9 }10};11module.exports = {12 'Test 1': function (browser) {13 .logScreenshot('Test 1', './reports/screenshots/test1.png')14 .end();15 },16 'Test 2': function (browser) {17 .logScreenshot('Test 2', './reports/screenshots/test2.png')18 .end();19 }20};21module.exports = {22 'Test 1': function (browser) {23 .logInfo('Test 1')24 .end();25 },26 'Test 2': function (browser) {27 .logInfo('Test 2')28 .end();29 }30};
Using AI Code Generation
1module.exports = {2 'Demo test Google' : function (browser) {3 .waitForElementVisible('body', 1000)4 .logTimestamp("log message")5 .end();6 }7};8 Licensed under the Apache License, Version 2.0 (the "License"); you may not
Using AI Code Generation
1module.exports = {2 'Test 1' : function (client) {3 .logTimestamp('Test 1: start')4 .logTimestamp('Test 1: end')5 .end();6 }7};8{9 "selenium" : {10 "cli_args" : {11 }12 },13 "test_settings" : {14 "default" : {15 "screenshots" : {16 },17 "desiredCapabilities": {18 }19 },20 "chrome" : {21 "desiredCapabilities": {22 }23 }24 }25}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!