Best JavaScript code snippet using cypress
start.spec.js
Source:start.spec.js
1const express = require('express');2const { expect } = require('chai');3const { killSpawnProcessAndHisChildren } = require('./helpers/process');4const tp = require('./helpers/test-phases');5const fx = require('./helpers/fixtures');6const fetch = require('node-fetch');7const retryPromise = require('retry-promise').default;8const { outsideTeamCity } = require('./helpers/env-variables');9const https = require('https');10describe('Aggregator: Start', () => {11 let test, child;12 describe('Yoshi', () => {13 beforeEach(() => {14 test = tp.create();15 child = null;16 });17 afterEach(() => {18 test.teardown();19 return killSpawnProcessAndHisChildren(child);20 });21 describe('tests', function() {22 it('should run tests initially', () => {23 child = test24 .setup({25 'src/test.spec.js': '',26 'src/client.js': '',27 'entry.js': '',28 'package.json': fx.packageJson(),29 'pom.xml': fx.pom(),30 })31 .spawn('start');32 return checkStdout('Testing with Mocha');33 });34 });35 describe('--debug', () => {36 it('should not pass --inspect flag when parameter is not passed', () => {37 const checkIfInspectIsPassedInArgs = function() {38 return !!process.execArgv.find(arg => arg.indexOf('--inspect') === 0);39 };40 child = test41 .setup({42 'src/client.js': '',43 'index.js': `console.log((${checkIfInspectIsPassedInArgs.toString()})())`,44 'package.json': fx.packageJson(),45 'pom.xml': fx.pom(),46 })47 .spawn('start');48 return checkServerLogContains('false', { backoff: 100 });49 });50 it('should pass --inspect flag when parameter is passed with the correct port', () => {51 const port = 9230;52 const checkIfInspectIsPassedInArgs = function(port) {53 return !!process.execArgv.find(54 arg => arg.indexOf(`--inspect=127.0.0.1:${port}`) === 0,55 );56 };57 child = test58 .setup({59 'src/client.js': '',60 'index.js': `console.log((${checkIfInspectIsPassedInArgs.toString()})(${port}))`,61 'package.json': fx.packageJson(),62 'pom.xml': fx.pom(),63 })64 .spawn('start', `--debug=${port}`);65 return checkServerLogContains('true', { backoff: 100 });66 });67 });68 describe('--entry-point', () => {69 it('should run the entry point provided and add .js to entry if needed', () => {70 child = test71 .setup({72 'src/client.js': '',73 'entry.js': `console.log('hello world!')`,74 'package.json': fx.packageJson(),75 'pom.xml': fx.pom(),76 })77 .spawn('start', '--entry-point=entry');78 return checkServerLogContains('hello world!');79 });80 it('should run index.js by default', () => {81 child = test82 .setup({83 'src/client.js': '',84 'index.js': `console.log('hello world!')`,85 'package.json': fx.packageJson(),86 'pom.xml': fx.pom(),87 })88 .spawn('start');89 return checkServerLogContains('hello world!');90 });91 });92 describe('--no-server', () => {93 it('should not start a server if --no-server is passed', () => {94 child = test95 .setup({96 'src/assets/image.png': '',97 'index.js': `console.log('should not run');`,98 'package.json': fx.packageJson({99 servers: { cdn: { port: 3005 } },100 }),101 '.babelrc': '{}',102 })103 .spawn('start', ['--no-server']);104 return cdnIsServing('assets/image.png').then(() =>105 expect(test.stdout).not.to.contain('should not run'),106 );107 });108 });109 describe('HMR', () => {110 it('should create bundle with enabled hot module replacement', () => {111 child = test112 .setup({113 'src/client.js': `module.exports.wat = 'hmr';\n`,114 'package.json': fx.packageJson(),115 })116 .spawn('start');117 return checkServerIsServing({ port: 3200, file: 'app.bundle.js' }).then(118 content => expect(content).to.contain('"hot":true'),119 );120 });121 it('should create bundle with disabled hot module replacement if there is {hmr: false} in config', () => {122 child = test123 .setup(124 {125 'src/client.js': `module.exports.wat = 'hmr';\n`,126 'package.json': fx.packageJson({ hmr: false }),127 },128 [],129 )130 .spawn('start');131 return checkServerIsServing({ port: 3200, file: 'app.bundle.js' }).then(132 content => expect(content).to.contain(`"hot":false`),133 );134 });135 it('should wrap react root element with react-hot-loader HOC', () => {136 child = test137 .setup({138 'src/client.js': `import { render } from 'react-dom';139 render(<App />, rootEl);`,140 '.babelrc': `{"presets": ["${require.resolve(141 'babel-preset-wix',142 )}"]}`,143 'package.json': fx.packageJson(144 {145 hmr: 'auto',146 entry: './client.js',147 },148 {149 react: '16.0.0',150 },151 ),152 })153 .spawn('start');154 return checkServerIsServing({ port: 3200, file: 'app.bundle.js' }).then(155 content => {156 expect(content).to.contain('module.hot.accept()');157 expect(content).to.contain('react-hot-loader');158 },159 );160 });161 it('should wrap react root element with react-hot-loader HOC for default entry', () => {162 child = test163 .setup({164 'src/client.js': `import { render } from 'react-dom';165 render(<App />, rootEl);`,166 '.babelrc': `{"presets": ["${require.resolve(167 'babel-preset-wix',168 )}"]}`,169 'package.json': fx.packageJson(170 {171 hmr: 'auto',172 },173 {174 react: '16.0.0',175 },176 ),177 })178 .spawn('start');179 return checkServerIsServing({ port: 3200, file: 'app.bundle.js' }).then(180 content => {181 expect(content).to.contain('module.hot.accept()');182 expect(content).to.contain('react-hot-loader');183 },184 );185 });186 });187 describe('Public path', () => {188 it('should set proper public path', () => {189 child = test190 .setup({191 'src/client.js': `module.exports.wat = 'hmr';\n`,192 'package.json': fx.packageJson(),193 })194 .spawn('start');195 return checkServerIsServing({ port: 3200, file: 'app.bundle.js' }).then(196 content =>197 expect(content).to.contain(198 `__webpack_require__.p = "http://localhost:3200/";`,199 ),200 );201 });202 it('should be able to set public path via servers.cdn.url', () => {203 child = test204 .setup({205 'src/client.js': `module.exports.wat = 'hmr';\n`,206 'package.json': fx.packageJson({207 servers: { cdn: { url: 'some.url' } },208 }),209 })210 .spawn('start');211 return checkServerIsServing({ port: 3200, file: 'app.bundle.js' }).then(212 content =>213 expect(content).to.contain(`__webpack_require__.p = "some.url";`),214 );215 });216 });217 describe('CDN server', () => {218 it('should serve files without "min" suffix when requested with a "min" suffix', () => {219 child = test220 .setup({221 'src/client.js': `module.exports = {};`,222 'package.json': fx.packageJson(),223 })224 .spawn('start');225 return checkServerIsServing({226 port: 3200,227 file: 'app.bundle.min.js',228 }).then(content => {229 expect(content).to.contain(230 `__webpack_require__.p = "http://localhost:3200/";`,231 );232 });233 });234 it('should serve files without "min" suffix when requested with a "min" suffix in ssl', () => {235 child = test236 .setup({237 'src/client.js': `module.exports = {};`,238 'package.json': fx.packageJson({ servers: { cdn: { ssl: true } } }),239 })240 .spawn('start');241 const agent = new https.Agent({242 rejectUnauthorized: false,243 });244 return checkServerIsServing({245 port: 3200,246 file: 'app.bundle.min.js',247 protocol: 'https',248 options: { agent },249 }).then(content =>250 expect(content).to.contain(251 `__webpack_require__.p = "https://localhost:3200/";`,252 ),253 );254 });255 it('should run cdn server with default dir', () => {256 child = test257 .setup({258 'src/assets/test.json': '{a: 1}',259 'src/index.js': 'var a = 1;',260 'package.json': fx.packageJson({261 servers: { cdn: { port: 3005 } },262 }),263 })264 .spawn('start');265 return cdnIsServing('assets/test.json');266 });267 it('should run cdn server with configured dir', () => {268 child = test269 .setup({270 'src/assets/test.json': '{a: 1}',271 'src/index.js': 'var a = 1;',272 'package.json': fx.packageJson({273 servers: { cdn: { port: 3005, dir: 'dist/statics' } },274 }),275 })276 .spawn('start');277 return cdnIsServing('assets/test.json');278 });279 it('should run cdn server from node_modules, on n-build project, using default dir', () => {280 child = test281 .setup({282 'node_modules/my-client-project/dist/test.json': '{a: 1}',283 'src/index.js': 'var a = 1;',284 'package.json': fx.packageJson({285 clientProjectName: 'my-client-project',286 servers: { cdn: { port: 3005 } },287 }),288 })289 .spawn('start');290 return cdnIsServing('test.json');291 });292 it('should run cdn server from node_modules, on n-build project, using configured dir', () => {293 child = test294 .setup({295 'node_modules/my-client-project/dist/statics/test.json': '{a: 1}',296 'src/index.js': 'var a = 1;',297 'package.json': fx.packageJson({298 clientProjectName: 'my-client-project',299 servers: { cdn: { port: 3005, dir: 'dist/statics' } },300 }),301 })302 .spawn('start');303 return cdnIsServing('test.json');304 });305 it('should support cross origin requests headers', () => {306 child = test307 .setup({308 'package.json': fx.packageJson(),309 })310 .spawn('start');311 return fetchCDN().then(res => {312 expect(res.headers.get('Access-Control-Allow-Methods')).to.equal(313 'GET, OPTIONS',314 );315 expect(res.headers.get('Access-Control-Allow-Origin')).to.equal('*');316 });317 });318 it('should support resource timing headers', () => {319 child = test320 .setup({321 'package.json': fx.packageJson(),322 })323 .spawn('start');324 return fetchCDN().then(res => {325 expect(res.headers.get('Timing-Allow-Origin')).to.equal('*');326 });327 });328 describe('HTTPS', () => {329 // This is because we're using self signed certificate - otherwise the request will fail330 const agent = new https.Agent({331 rejectUnauthorized: false,332 });333 it('should be able to create an https server', () => {334 child = test335 .setup({336 'src/assets/test.json': '{a: 1}',337 'src/index.js': 'var a = 1;',338 'package.json': fx.packageJson({339 servers: {340 cdn: { port: 3005, dir: 'dist/statics', ssl: true },341 },342 }),343 })344 .spawn('start');345 return cdnIsServing('assets/test.json', 3005, 'https', { agent });346 });347 it('should enable ssl when ran --ssl', () => {348 child = test349 .setup({350 'src/assets/test.json': '{a: 1}',351 'src/index.js': 'var a = 1;',352 'package.json': fx.packageJson({353 servers: { cdn: { port: 3005, dir: 'dist/statics' } },354 }),355 })356 .spawn('start', '--ssl');357 return cdnIsServing('assets/test.json', 3005, 'https', { agent });358 });359 });360 });361 describe('when the default port is taken', () => {362 let server;363 beforeEach(() => (server = takePort(3000)));364 afterEach(() => server.close());365 it('it should use the next available port', () => {366 child = test367 .setup({368 'index.js': `console.log('port', process.env.PORT)`,369 'package.json': fx.packageJson(),370 })371 .spawn('start');372 return checkServerLogContains('port 3001');373 });374 });375 describe('Watch', function() {376 this.timeout(30000);377 describe('when using typescript', () => {378 it(`should rebuild and restart server after a file has been changed with typescript files`, () => {379 child = test380 .setup({381 'tsconfig.json': fx.tsconfig(),382 'src/server.ts': `declare var require: any; ${fx.httpServer(383 'hello',384 )}`,385 'src/config.ts': '',386 'src/client.ts': '',387 'index.js': `require('./dist/src/server')`,388 'package.json': fx.packageJson(),389 'pom.xml': fx.pom(),390 })391 .spawn('start');392 return checkServerIsServing({ max: 100 })393 .then(() => checkServerIsRespondingWith('hello'))394 .then(() =>395 test.modify(396 'src/server.ts',397 `declare var require: any; ${fx.httpServer('world')}`,398 ),399 )400 .then(() => {401 return checkServerIsRespondingWith('world');402 });403 });404 });405 describe('when using es6', () => {406 it(`should rebuild and restart server after a file has been changed`, () => {407 child = test408 .setup({409 'src/server.js': fx.httpServer('hello'),410 'src/config.js': '',411 'src/client.js': '',412 'index.js': `require('./src/server')`,413 'package.json': fx.packageJson(),414 'pom.xml': fx.pom(),415 '.babelrc': '{}',416 })417 .spawn('start');418 return checkServerIsServing()419 .then(() => checkServerIsRespondingWith('hello'))420 .then(() => test.modify('src/server.js', fx.httpServer('world')))421 .then(() => checkServerIsRespondingWith('world'));422 });423 });424 describe('when using no transpile', () => {425 it(`should restart server after a file has been changed`, () => {426 child = test427 .setup({428 'src/server.js': fx.httpServer('hello'),429 'src/config.js': '',430 'src/client.js': '',431 'index.js': `require('./src/server')`,432 'package.json': fx.packageJson(),433 'pom.xml': fx.pom(),434 })435 .spawn('start');436 return checkServerIsServing()437 .then(() => checkServerIsRespondingWith('hello'))438 .then(() => test.modify('src/server.js', fx.httpServer('world')))439 .then(() => checkServerIsRespondingWith('world'));440 });441 });442 describe('client side code', () => {443 it('should recreate and serve a bundle after file changes', () => {444 const file = { port: 3200, file: 'app.bundle.js' };445 const newSource = `module.exports = 'wat';\n`;446 child = test447 .setup({448 'src/client.js': `module.exports = function () {};\n`,449 'package.json': fx.packageJson(),450 })451 .spawn('start');452 return checkServerIsServing(file)453 .then(() => test.modify('src/client.js', newSource))454 .then(() => checkServerReturnsDifferentContent(file))455 .then(content => expect(content).to.contain(newSource));456 });457 });458 describe('with --manual-restart flag', () => {459 beforeEach(() => {460 child = test461 .setup({462 'src/someFile.js': '',463 'index.js': `464 console.log('onInit');465 setInterval(() => {}, 1000);466 process.on('SIGHUP', () => console.log('onRestart'));467 `,468 'package.json': fx.packageJson(),469 '.babelrc': '{}',470 })471 .spawn('start', ['--manual-restart']);472 });473 it('should send SIGHUP to entryPoint process on change', () =>474 checkServerLogContains('onInit').then(() =>475 triggerChangeAndCheckForRestartMessage(),476 ));477 it('should not restart server', () =>478 checkServerLogContains('onInit', { backoff: 200 })479 .then(() => triggerChangeAndCheckForRestartMessage())480 .then(() => expect(serverLogContent()).to.not.contain('onInit')));481 function triggerChangeAndCheckForRestartMessage() {482 clearServerLog();483 test.modify('src/someFile.js', ' ');484 return checkServerLogContains('onRestart', { backoff: 200 });485 }486 });487 });488 it('should use yoshi-update-node-version', () => {489 child = test490 .setup({491 'src/test.spec.js': '',492 'src/client.js': '',493 'entry.js': '',494 'package.json': fx.packageJson(),495 'pom.xml': fx.pom(),496 })497 .spawn('start', [], outsideTeamCity);498 return checkServerLogCreated().then(499 () => expect(test.contains('.nvmrc')).to.be.true,500 );501 });502 it(`should use yoshi-clean before building`, () => {503 child = test504 .setup({505 'dist/src/old.js': `const hello = "world!";`,506 'src/new.js': 'const world = "hello!";',507 'package.json': fx.packageJson(),508 '.babelrc': '{}',509 })510 .spawn('start');511 return checkServerLogCreated().then(() => {512 expect(test.stdout).to.contains(`Finished 'clean'`);513 expect(test.list('dist')).to.not.include('old.js');514 expect(test.list('dist/src')).to.include('new.js');515 });516 });517 describe('when there are runtime errors', () => {518 it('should display a warning message on the terminal', () => {519 child = test520 .setup({521 'index.js': `throw new Error('wix:error')`,522 'package.json': fx.packageJson(),523 'pom.xml': fx.pom(),524 })525 .spawn('start');526 return checkServerLogCreated()527 .then(wait(1000))528 .then(() =>529 expect(test.stdout).to.contains(530 `There are errors! Please check ./target/server.log`,531 ),532 );533 });534 });535 describe('Migrate Bower Artifactory', () => {536 it('should migrate .bowerrc', () => {537 const bowerrc = {538 registry: {539 search: [540 'https://bower.herokuapp.com',541 'http://wix:wix@mirror.wixpress.com:3333',542 ],543 register: 'http://wix:wix@mirror.wixpress.com:3333',544 publish: 'http://wix:wix@mirror.wixpress.com:3333',545 },546 };547 child = test548 .setup({549 'package.json': fx.packageJson(),550 '.bowerrc': JSON.stringify(bowerrc, null, 2),551 })552 .spawn('start');553 return retryPromise({ backoff: 100 }, () => {554 try {555 const newBowerrc = JSON.parse(test.content('.bowerrc'));556 expect(newBowerrc).to.eql({557 registry: 'https://bower.dev.wixpress.com',558 resolvers: ['bower-art-resolver'],559 });560 const newPj = JSON.parse(test.content('package.json'));561 expect(newPj.devDependencies['bower-art-resolver']).to.exist;562 return Promise.resolve();563 } catch (e) {564 return Promise.reject(e);565 }566 });567 });568 });569 });570 function checkServerLogCreated({ backoff = 100 } = {}) {571 return retryPromise(572 { backoff },573 () =>574 test.contains('target/server.log')575 ? Promise.resolve()576 : Promise.reject(new Error('No server.log found')),577 );578 }579 function serverLogContent() {580 return test.content('target/server.log');581 }582 function clearServerLog() {583 test.write('target/server.log', '');584 }585 function checkServerLogContains(str, { backoff = 100 } = {}) {586 return checkServerLogCreated({ backoff }).then(() =>587 retryPromise({ backoff }, () => {588 const content = serverLogContent();589 return content.includes(str)590 ? Promise.resolve()591 : Promise.reject(592 new Error(593 `Expect server.log to contain "${str}", got "${content}" instead`,594 ),595 );596 }),597 );598 }599 function checkStdout(str) {600 return retryPromise(601 { backoff: 100 },602 () =>603 test.stdout.indexOf(str) > -1 ? Promise.resolve() : Promise.reject(),604 );605 }606 function takePort(port) {607 return express().listen(port);608 }609 function fetchCDN(port) {610 port = port || 3200;611 return retryPromise({ backoff: 100 }, () =>612 fetch(`http://localhost:${port}/`),613 );614 }615 function cdnIsServing(name, port = 3005, protocol = 'http', options = {}) {616 return retryPromise({ backoff: 100 }, () =>617 fetch(`${protocol}://localhost:${port}/${name}`, options).then(res => {618 expect(res.status).to.equal(200);619 return res.text();620 }),621 );622 }623 function checkServerIsRespondingWith(expected) {624 return retryPromise({ backoff: 1000 }, () =>625 fetch(`http://localhost:${fx.defaultServerPort()}/`)626 .then(res => res.text())627 .then(628 body => (body === expected ? Promise.resolve() : Promise.reject()),629 ),630 );631 }632 function wait(time) {633 return () => new Promise(resolve => setTimeout(resolve, time));634 }635 function checkServerIsServing({636 backoff = 100,637 max = 10,638 port = fx.defaultServerPort(),639 file = '',640 protocol = 'http',641 options = {},642 } = {}) {643 return retryPromise({ backoff, max }, () =>644 fetch(`${protocol}://localhost:${port}/${file}`, options).then(res =>645 res.text(),646 ),647 );648 }649 function checkServerReturnsDifferentContent({650 backoff = 100,651 max = 10,652 port = fx.defaultServerPort(),653 file = '',654 } = {}) {655 const url = `http://localhost:${port}/${file}`;656 let response;657 return retryPromise(658 { backoff, max },659 () =>660 new Promise((resolve, reject) =>661 fetch(url)662 .then(res => res.text())663 .then(content => {664 if (response && response !== content) {665 resolve(content);666 } else {667 reject(`response of ${url} did not change`);668 }669 response = content;670 })671 .catch(reject),672 ),673 );674 }...
index.js
Source:index.js
1const botconfig = require("./botconfig.json");2const tokenfile = botconfig.token;3const Discord = require("Discord.js");4const fs = require("fs");5const bot = new Discord.Client({DisableEveryone: true});6bot.commands = new Discord.Collection();7const Enmap = require("enmap")89bot.on("ready", async () => {10 console.log(`${bot.user.username} is online!`);11 bot.user.setActivity("Black Desert Online", {type: "PLAYING"});;12});1314fs.readdir("./commands/", (err, files) => {15 if (err) return console.error(err);16 files.forEach(file => {17 let eventFunction = require(`./commands/${file}`);18 let eventName = file.split(".")[0];19 20 bot.on(eventName, (...args) => eventFunction.run(bot, ...args));21 });22 });2324 bot.on("message", message => {25 if (message.author.bot) return;26 if(message.content.indexOf(botconfig.prefix) !== 0) return;27 2829 const args = message.content.slice(botconfig.prefix.length).trim().split(/ +/g);30 const command = args.shift().toLowerCase();31 3233 try {34 let commandFile = require(`./commands/${command}.js`);35 commandFile.run(bot, message, args);36 } catch (err) {37 console.error(err);38 }39 });40414243 44 45 //Kutum46 const cron = require('node-cron');47 var schedule = require('node-schedule');4849 var task = cron.schedule('05 00 * * 1,3,7', () => {50 let kutum = require('./Schedule/boss.js');51 bot.channels.get(botconfig.channel).send({embed: kutum});52 console.log('Boss Spawn');53 }, {54 55 start: true,56 scheduled: true,57 58 });596061 var kutum2 = cron.schedule('50 01 * * 2,4', () => {62 let kutum = require('./Schedule/boss.js');63 bot.channels.get(botconfig.channel).send({embed: kutum});64 console.log('Boss Spawn');65 }, {66 67 start: true,68 scheduled: true,69 70 });71// 72var kutum3 = cron.schedule('50 04 * * 0', () => {73 let kutum = require('./Schedule/boss.js');74 bot.channels.get(botconfig.channel).send({embed: kutum});75 console.log('Boss Spawn');76}, {7778start: true,79scheduled: true,8081});82// 83var kutum4 = cron.schedule('50 08 * * 2,4,5,6', () => {84 let kutum = require('./Schedule/boss.js');85 bot.channels.get(botconfig.channel).send({embed: kutum});86 console.log('Boss Spawn');87}, {8889start: true,90scheduled: true,9192}); 9394var kutum5 = cron.schedule('50 15 * * 1,4', () => {95 let kutum = require('./Schedule/boss.js');96 bot.channels.get(botconfig.channel).send({embed: kutum});97 console.log('Boss Spawn');98}, {99100start: true,101scheduled: true,102103}); 104105var kutum6 = cron.schedule('50 18 * * 3', () => {106 let kutum = require('./Schedule/boss.js');107 bot.channels.get(botconfig.channel).send({embed: kutum});108 console.log('Boss Spawn');109}, {110111start: true,112scheduled: true,113114}); 115116var kutum7 = cron.schedule('05 22 * * 5', () => {117 let kutum = require('./Schedule/boss.js');118 bot.channels.get(botconfig.channel).send({embed: kutum});119 console.log('Boss Spawn');120}, {121122start: true,123scheduled: true,124125});126// //Karanda127var Karanda1 = cron.schedule('05 00 * * 2,6', () => {128 let karanda = require('./Schedule/karanda.js');129 bot.channels.get(botconfig.channel).send({embed: karanda});130 console.log('Boss Spawn');131}, {132133start: true,134scheduled: true,135136});137var Karanda2 = cron.schedule('50 01 * * 1,3', () => {138 let karanda = require('./Schedule/karanda.js');139 bot.channels.get(botconfig.channel).send({embed: karanda});140 console.log('Boss Spawn');141}, {142143start: true,144scheduled: true,145146});147 148var Karanda3 = cron.schedule('50 04 * * 5', () => {149 let karanda = require('./Schedule/karanda.js');150 bot.channels.get(botconfig.channel).send({embed: karanda});151 console.log('Boss Spawn');152}, {153154start: true,155scheduled: true,156157});158var Karanda4 = cron.schedule('50 08 * * 3', () => {159 let karanda = require('./Schedule/karanda.js');160 bot.channels.get(botconfig.channel).send({embed: karanda});161 console.log('Boss Spawn');162}, {163164start: true,165scheduled: true,166167});168var Karanda5 = cron.schedule('50 11 * * 5', () => {169 let karanda = require('./Schedule/karanda.js');170 bot.channels.get(botconfig.channel).send({embed: karanda});171 console.log('Boss Spawn');172}, {173174start: true,175scheduled: true,176177});178var Karanda6 = cron.schedule('50 18 * * 0,2,6', () => {179 let karanda = require('./Schedule/karanda.js');180 bot.channels.get(botconfig.channel).send({embed: karanda});181 console.log('Boss Spawn');182}, {183184start: true,185scheduled: true,186187});188var Karanda7 = cron.schedule('05 22 * * 3,4', () => {189 let karanda = require('./Schedule/karanda.js');190 bot.channels.get(botconfig.channel).send({embed: karanda});191 console.log('Boss Spawn');192}, {193194start: true,195scheduled: true,196197});198// //Kzarka199var Kzarka1 = cron.schedule('05 00 * * 5', () => {200 let Kzarka = require('./Schedule/Kzarka.js');201 bot.channels.get(botconfig.channel).send({embed: Kzarka});202 console.log('Boss Spawn');203}, {204205start: true,206scheduled: true,207208});209var Kzarka2 = cron.schedule('50 01 * * 0', () => {210 let Kzarka = require('./Schedule/Kzarka.js');211 bot.channels.get(botconfig.channel).send({embed: Kzarka});212 console.log('Boss Spawn');213}, {214215start: true,216scheduled: true,217218});219 220var Kzarka3 = cron.schedule('50 04 * * 1,2,3', () => {221 let Kzarka = require('./Schedule/Kzarka.js');222 bot.channels.get(botconfig.channel).send({embed: Kzarka});223 console.log('Boss Spawn');224}, {225226start: true,227scheduled: true,228229});230 231var Kzarka4 = cron.schedule('50 08 * * 1', () => {232 let Kzarka = require('./Schedule/Kzarka.js');233 bot.channels.get(botconfig.channel).send({embed: Kzarka});234 console.log('Boss Spawn');235}, {236237start: true,238scheduled: true,239240});241var Kzarka5 = cron.schedule('50 11 * * 0', () => {242 let Kzarka = require('./Schedule/Kzarka.js');243 bot.channels.get(botconfig.channel).send({embed: Kzarka});244 console.log('Boss Spawn');245}, {246247start: true,248scheduled: true,249250});251var Kzarka6 = cron.schedule('50 15 * * 3', () => {252 let Kzarka = require('./Schedule/Kzarka.js');253 bot.channels.get(botconfig.channel).send({embed: Kzarka});254 console.log('Boss Spawn');255}, {256257start: true,258scheduled: true,259260});261var Kzarka7 = cron.schedule('50 18 * * 5,6', () => {262 let Kzarka = require('./Schedule/Kzarka.js');263 bot.channels.get(botconfig.channel).send({embed: Kzarka});264 console.log('Boss Spawn');265}, {266267start: true,268scheduled: true,269timeZone: 'Europe/Madrid'270});271var Kzarka8 = cron.schedule('05 22 * * 1,2,3,5,7', () => {272 let Kzarka = require('./Schedule/Kzarka.js');273 bot.channels.get(botconfig.channel).send({embed: Kzarka});274 console.log('Boss Spawn');275}, {276277start: true,278scheduled: true,279timeZone: 'Europe/Madrid'280});281282// //Nouver283var Nouver1 = cron.schedule('05 00 * * 4,7', () => {284 let Nouver = require('./Schedule/Nouver.js');285 bot.channels.get(botconfig.channel).send({embed: Nouver});286 console.log('Boss Spawn');287}, {288289start: true,290scheduled: true,291292});293var Nouver2 = cron.schedule('50 01 * * 5', () => {294 let Nouver = require('./Schedule/Nouver.js');295 bot.channels.get(botconfig.channel).send({embed: Nouver});296 console.log('Boss Spawn');297}, {298299start: true,300scheduled: true,301302});303 304var Nouver3 = cron.schedule('50 04 * * 4,6', () => {305 let Nouver = require('./Schedule/Nouver.js');306 bot.channels.get(botconfig.channel).send({embed: Nouver});307 console.log('Boss Spawn');308}, {309310start: true,311scheduled: true,312313});314var Nouver4 = cron.schedule('50 08 * * 0', () => {315 let Nouver = require('./Schedule/Nouver.js');316 bot.channels.get(botconfig.channel).send({embed: Nouver});317 console.log('Boss Spawn');318}, {319320start: true,321scheduled: true,322323});324var Nouver5 = cron.schedule('50 11 * * 1,4,6', () => {325 let Nouver = require('./Schedule/Nouver.js');326 bot.channels.get(botconfig.channel).send({embed: Nouver});327 console.log('Boss Spawn');328}, {329330start: true,331scheduled: true,332333});334var Nouver6 = cron.schedule('50 15 * * 2,5', () => {335 let Nouver = require('./Schedule/Nouver.js');336 bot.channels.get(botconfig.channel).send({embed: Nouver});337}, {338339start: true,340scheduled: true,341342});343var Nouver7 = cron.schedule('50 18 * * 1', () => {344 let Nouver = require('./Schedule/Nouver.js');345 bot.channels.get(botconfig.channel).send({embed: Nouver});346 console.log('Boss Spawn');347}, {348349start: true,350scheduled: true,351352});353var Nouver8 = cron.schedule('5 22 * * 0,2', () => {354 let Nouver = require('./Schedule/Nouver.js');355 bot.channels.get(botconfig.channel).send({embed: Nouver});356 console.log('Boss Spawn');357}, {358359start: true,360scheduled: true,361362});363364// //Offin365var Offin1 = cron.schedule('50 01 * * 6', () => {366 let Offin = require('./Schedule/Offin.js');367 bot.channels.get(botconfig.channel).send({embed: Offin});368 console.log('Boss Spawn');369}, {370371start: true,372scheduled: true,373374}); 375var Offin2 = cron.schedule('50 11 * * 2', () => {376 let Offin = require('./Schedule/Offin.js');377 bot.channels.get(botconfig.channel).send({embed: Offin});378 console.log('Boss Spawn');379}, {380381start: true,382scheduled: true,383384}); 385 386var Offin3 = cron.schedule('50 18 * * 4', () => {387 let Offin = require('./Schedule/Offin.js');388 bot.channels.get(botconfig.channel).send({embed: Offin});389 console.log('Boss Spawn');390}, {391392start: true,393scheduled: true,394395}); 396397// //Vell398var Vell = cron.schedule('50 15 * * 7', () => {399 let Vell = require('./Schedule/Vell.js');400 bot.channels.get(botconfig.channel).send({embed: Vell});401 console.log('Boss Spawn');402}, {403404start: true,405scheduled: true,406407}); 408 console.log('Scheduler is feeling happy!');409410411 412413 414415416
...
game.js
Source:game.js
1//get playerID from passed url2var playerID = location.search.split('playerID=')[1];3//setup Quintus game engine4var Q = window.Q = Quintus({development: true}).include("Scenes, Sprites, 2D, Input, Touch, UI, TMX, Audio, Anim");5Q.setup("game",{6 "scaleToFit": true,7 "width": 800,8 "height":8009 }).touch(Q.SPRITE_ALL);10//Q.setup("game").touch(Q.SPRITE_ALL);11//setup socket12var socket = Q.socket = io.connect('http://localhost:1337');13//fetch the rest of necessary player data for the level14socket.on("gameInitData", function(data){15 Q.ROLE = data.players[playerID-1].role;16 console.log(Q.ROLE);17});18//initialize global variables19Q.SPRITE_CAR = 1;20Q.SPRITE_DIRECTION = 2;21Q.SPRITE_SPAWN = 4;22//enable inputs23Q.input.keyboardControls();24Q.input.joypadControls();25//disable gravity26Q.gravityY = 0;27Q.gravityX = 0;28Q.SCORE = 0;29Q.SPEED = 10;30Q.DELAY = 10;31Q.SUCCESS = 10;32Q.FAIL = 5;33// create general component for directions34/*Q.component("direction", {35 added: function() {36 var entity = this.entity;37 entity.on("click", function() {38 console.log("direction clicked!");39 });40 }41});*/42// insert direction pointers43/*Q.Sprite.extend("Left", {44 init: function(p) {45 this._super(p, { });46 //this.add("direction");47 console.log("left");48 }49});*/50var spawns = [];51Q.Sprite.extend("Spawn", {52 init: function(p) {53 var openVX = 0;54 var openVY = 0;55 if(p.direction=="Left"){56 openVX = 1 * Q.SPEED;57 openVY = 0;58 } else if(p.direction=="Down"){59 openVX = 0;60 openVY = -1 * Q.SPEED;61 } else if(p.direction=="Right"){62 openVX = -1 * Q.SPEED;63 openVY = 0;64 } else if(p.direction=="Up"){65 openVX = 0;66 openVY = 1 * Q.SPEED;67 }68 this._super(p, {69 type: Q.SPRITE_SPAWN,70 collisionMask: Q.SPRITE_CAR,71 openVX: openVX,72 openVY: openVY,73 });74 spawns[spawns.length] = this;75 }76});77var directions = [];78Q.Sprite.extend("Direction", {79 init: function(p) {80 this._super(p, {81 type: Q.SPRITE_DIRECTION,82 collisionMask: Q.SPRITE_NONE,83 sensor: true,84 });85 this.on("touch");86 this.on("sensor");87 directions.push(this);88 },89 touch: function(touch) {90 if(Q.ROLE === "operator"){91 if(touch.obj.p.sheet=="Left"){92 touch.obj.p.sheet="Down";93 }else if(touch.obj.p.sheet=="Down"){94 touch.obj.p.sheet="Right";95 }else if(touch.obj.p.sheet=="Right"){96 touch.obj.p.sheet="Up";97 }else if(touch.obj.p.sheet=="Up"){98 touch.obj.p.sheet="Left";99 }100 socket.emit("directionChanged", {"id":touch.obj.p.id, "dir":touch.obj.p.sheet});101 }102 },103 sensor: function(col) {104 if(playerID==1){105 col.p.sensorDirection = this;106 }107 }108 });109//change direction on remote directionChanged event110socket.on("directionChanged", function(data){111 for(var i = 0; i < directions.length; i++) {112 if(directions[i].p.id==data.id){113 directions[i].p.sheet=data.dir;114 }115 }116});117var carCount = 0;118var spawnedCars = new Object();119Q.Sprite.extend("Car", {120 init: function(data) {121 //kind of cars122 var cars = ["Car_Red","Car_Blue","Car_Yellow"];123 if(typeof data !== "undefined"){124 this._super({125 carid: data.carid,126 vx: 0,127 vy: 0,128 type: Q.SPRITE_CAR,129 collisionMask: Q.SPRITE_SPAWN | Q.SPRITE_DIRECTION,130 spawnStart: spawns[data.spawnStartId],131 spawnTarget: spawns[data.spawnTargetId],132 x: data.x,133 y: data.y,134 lastX: 0,135 lastY: 0,136 sensorDirection: data.sensorDirection,137 sheet: data.sheet,138 identifyTarget: data.identifyTarget,139 //x = spawnStart.140 });141 142 this.on("touch");143 this.add("2d");144 }else{145 146 //what car to spawn147 var carId = Math.floor(Math.random() * (cars.length-1));148 //get start and target spawn points149 var spawnStartId = Math.floor(Math.random()*(spawns.length-1));150 var spawnTargetId = Math.floor(Math.random()*(spawns.length-1));151 while(spawnStartId==spawnTargetId){152 spawnTargetId = Math.floor(Math.random()*(spawns.length-1));153 }154 //set initial movement155 var vx = 0;156 var vy = 0;157 if(spawns[spawnStartId].p.direction=="Left"){158 vx = -1 * Q.SPEED;159 vy = 0;160 }else if(spawns[spawnStartId].p.direction=="Down"){161 vx = 0;162 vy = 1 * Q.SPEED;163 }else if(spawns[spawnStartId].p.direction=="Right"){164 vx = 1 * Q.SPEED;165 vy = 0;166 }else if(spawns[spawnStartId].p.direction=="Up"){167 vx = 0;168 vy = -1 * Q.SPEED;169 }170 carCount++;171 this._super({172 carid: carCount,173 vx: vx,174 vy: vy,175 type: Q.SPRITE_CAR,176 collisionMask: Q.SPRITE_SPAWN | Q.SPRITE_DIRECTION,177 spawnStart: spawns[spawnStartId],178 spawnTarget: spawns[spawnTargetId],179 x: spawns[spawnStartId].p.x,180 y: spawns[spawnStartId].p.y,181 lastX: 0,182 lastY: 0,183 sensorDirection: false,184 sheet: cars[carId],185 identifyTarget: 0,186 //x = spawnStart.187 });188 this.on("touch");189 190 if(playerID==1){191 this.on("hit");192 }193 this.add("2d");194 //console.log(this.p.spawnStart);195 socket.emit("newCar", {196 "carid":this.p.carid,197 "vx":this.p.vx,198 "vy":this.p.vy,199 "type":this.p.type,200 "collisionMask":this.p.collisionMask,201 "spawnStartId":spawnStartId,202 "spawnTargetId":spawnTargetId,203 "x":this.p.x,204 "y":this.p.y,205 "lastX":this.p.lastX,206 "lastY":this.p.lastY,207 "sensorDirection":this.p.sensorDirection,208 "sheet": this.p.sheet,209 "identifyTarget": this.p.identifyTarget});210 }211 spawnedCars[this.p.carid] = this;212 },213 step: function(dt) {214 if(playerID==1){215 //restore last movement216 var lastX = this.p.lastX;217 var lastY = this.p.lastY;218 //calculate next movement219 var nextX = this.p.x + this.p.vx * dt;220 var nextY = this.p.y + this.p.vy * dt;221 //calculate change of direction222 if(this.p.sensorDirection != false){223 //sensor detected224 if((this.p.sensorDirection.p.sheet == "Left" && this.p.vx <= 0) ||225 (this.p.sensorDirection.p.sheet == "Down" && this.p.vy >= 0) ||226 (this.p.sensorDirection.p.sheet == "Right" && this.p.vx >= 0) ||227 (this.p.sensorDirection.p.sheet == "Up" && this.p.vy <= 0)){228 229 var dirX = this.p.sensorDirection.p.x;230 var dirY = this.p.sensorDirection.p.y;231 var restDist = 0.0;232 if(this.p.vx == 0 && this.p.vy != 0){233 if(lastY >= dirY && dirY > nextY){234 restDist = dirY-nextY;235 }else if(lastY <= dirY && dirY < nextY){236 restDist = nextY-dirY;237 }else{238 //no step over center239 }240 }else if(this.p.vy == 0 && this.p.vx != 0){241 if(lastX >= dirX && dirX > nextX){242 restDist = dirX-nextX;243 }else if(lastX <= dirX && dirX < nextX){244 restDist = nextX-dirX;245 }else{246 //no step over center247 }248 }else{249 console.log("Car has no speed!");250 }251 252 if(restDist > 0.0){253 if(this.p.sensorDirection.p.sheet == "Left"){254 this.p.vx = -1 * Q.SPEED;255 this.p.vy = 0;256 nextX = this.p.sensorDirection.p.x-restDist;257 nextY = this.p.sensorDirection.p.y;258 }else if(this.p.sensorDirection.p.sheet == "Down"){259 this.p.vx = 0;260 this.p.vy = 1 * Q.SPEED;261 nextX = this.p.sensorDirection.p.x;262 nextY = this.p.sensorDirection.p.y+restDist;263 }else if(this.p.sensorDirection.p.sheet == "Right"){264 this.p.vx = 1 * Q.SPEED;265 this.p.vy = 0;266 nextX = this.p.sensorDirection.p.x+restDist;267 nextY = this.p.sensorDirection.p.y;268 }else if(this.p.sensorDirection.p.sheet == "Up"){269 this.p.vx = 0;270 this.p.vy = -1 * Q.SPEED;271 nextX = this.p.sensorDirection.p.x;272 nextY = this.p.sensorDirection.p.y-restDist;273 }274 }275 276 }277 //store movement as last movement and apply movement278 this.p.lastX = nextX;279 this.p.lastY = nextY;280 this.p.x = nextX; 281 this.p.y = nextY; 282 //reset direction sensor283 this.p.sensorDirection = false;284 }else{285 }286 287 socket.emit("carUpdate", {"carid": this.p.carid, "x": this.p.x, "y": this.p.y});288 }289 //identifiy target when clicked290 if(this.p.identifyTarget > 0){291 if(Math.floor(this.p.identifyTarget/0.2)%2==0){292 this.p.spawnTarget.p.opacity = 0.2;293 }else if (Math.floor(this.p.identifyTarget/0.2)%2==1){294 this.p.spawnTarget.p.opacity = 1;295 }else{296 console.log("identifiy target error")297 }298 }else{299 this.p.identifyTarget = 0;300 this.p.spawnTarget.p.opacity = 1;301 }302 this.p.identifyTarget -=dt;303 304 },305 touch: function(touch) {306 if(Q.ROLE === "disponent"){307 this.p.identifyTarget = 1;308 }309 },310 hit: function(col) {311 if(playerID==1){312 if(col.obj.isA("Spawn")){313 if(col.obj.p.openVX == this.p.vx && col.obj.p.openVY == this.p.vy){314 if(col.obj == this.p.spawnTarget){315 Q.SCORE += Q.SUCCESS;316 }else{317 Q.SCORE -= Q.FAIL;318 }319 console.log(Q.SCORE);320 this.destroy();321 socket.emit("carHitSpawn", {"carid":this.p.carid, "score":Q.SCORE});322 }323 }324 }325 }326});327socket.on("carHitSpawn",function(data){328 spawnedCars[data.carid].destroy();329 Q.SCORE = data.score;330 console.log(Q.SCORE);331});332socket.on("newCar", function(data){333 if(playerID != 1){334 Q.stages[Q.activeStage].insert(new Q.Car(data));335 }336});337socket.on("carUpdate",function(data){338 //console.log(data);339 //console.log(spawnedCars);340 spawnedCars[data.carid].p.x = data.x;341 spawnedCars[data.carid].p.y = data.y;342});343Q.GameObject.extend("CarSpawn", {344 init: function() {345 this.p = {346 spawn: 0,347 spawnDelay: Q.DELAY,348 };349 },350 update: function(dt) {351 this.p.spawn -= dt;352 if(this.p.spawn < 0){353 //spawn actually354 this.stage.insert(new Q.Car());355 //update next spawn time356 this.p.spawn = this.p.spawnDelay;357 }358 }359});360//define initial scene361Q.scene("levelStart", function(stage) {362 Q.stageTMX("level_test.tmx", stage);363 //window.stage = stage;364 if(playerID==1){365 stage.insert(new Q.CarSpawn());366 }367});368//console.log("defined scene");369//load assets370Q.loadTMX("level_test.tmx, spritesheet.png, sprites.json, sprites.png", function() {371 Q.compileSheets("sprites.png", "sprites.json");372 Q.stageScene("levelStart");373 socket.emit("gameInit");374});...
spawn_spec.js
Source:spawn_spec.js
...41 })42 context('.start', function () {43 it('passes args + options to spawn', function () {44 this.spawnedProcess.on.withArgs('close').yieldsAsync(0)45 return spawn.start('--foo', { foo: 'bar' })46 .then(() => {47 expect(cp.spawn).to.be.calledWithMatch('/path/to/cypress', [48 '--foo',49 '--cwd',50 cwd,51 ], {52 foo: 'bar',53 })54 })55 })56 it('uses npm command when running in dev mode', function () {57 this.spawnedProcess.on.withArgs('close').yieldsAsync(0)58 const p = path.resolve('..', 'scripts', 'start.js')59 return spawn.start('--foo', { dev: true, foo: 'bar' })60 .then(() => {61 expect(cp.spawn).to.be.calledWithMatch('node', [62 p,63 '--foo',64 '--cwd',65 cwd,66 ], {67 foo: 'bar',68 })69 })70 })71 it('starts xvfb when needed', function () {72 xvfb.isNeeded.returns(true)73 this.spawnedProcess.on.withArgs('close').yieldsAsync(0)74 return spawn.start('--foo')75 .then(() => {76 expect(xvfb.start).to.be.calledOnce77 })78 })79 it('does not start xvfb when its not needed', function () {80 this.spawnedProcess.on.withArgs('close').yieldsAsync(0)81 return spawn.start('--foo')82 .then(() => {83 expect(xvfb.start).not.to.be.called84 })85 })86 it('stops xvfb when spawn closes', function () {87 xvfb.isNeeded.returns(true)88 this.spawnedProcess.on.withArgs('close').yieldsAsync(0)89 this.spawnedProcess.on.withArgs('close').yields()90 return spawn.start('--foo')91 .then(() => {92 expect(xvfb.stop).to.be.calledOnce93 })94 })95 it('resolves with spawned close code in the message', function () {96 this.spawnedProcess.on.withArgs('close').yieldsAsync(10)97 return spawn.start('--foo')98 .then((code) => {99 expect(code).to.equal(10)100 })101 })102 it('rejects with error from spawn', function () {103 const msg = 'the error message'104 this.spawnedProcess.on.withArgs('error').yieldsAsync(new Error(msg))105 return spawn.start('--foo')106 .then(() => {107 throw new Error('should have hit error handler but did not')108 }, (e) => {109 expect(e.message).to.include(msg)110 })111 })112 it('unrefs if options.detached is true', function () {113 this.spawnedProcess.on.withArgs('close').yieldsAsync(0)114 return spawn.start(null, { detached: true })115 .then(() => {116 expect(this.spawnedProcess.unref).to.be.calledOnce117 })118 })119 it('does not unref by default', function () {120 this.spawnedProcess.on.withArgs('close').yieldsAsync(0)121 return spawn.start()122 .then(() => {123 expect(this.spawnedProcess.unref).not.to.be.called124 })125 })126 it('sets process.env to options.env', function () {127 this.spawnedProcess.on.withArgs('close').yieldsAsync(0)128 process.env.FOO = 'bar'129 return spawn.start()130 .then(() => {131 expect(cp.spawn.firstCall.args[2].env.FOO).to.eq('bar')132 })133 })134 it('forces colors and streams when supported', function () {135 this.spawnedProcess.on.withArgs('close').yieldsAsync(0)136 sinon.stub(util, 'supportsColor').returns(true)137 sinon.stub(tty, 'isatty').returns(true)138 return spawn.start([], { env: {} })139 .then(() => {140 expect(cp.spawn.firstCall.args[2].env).to.deep.eq({141 FORCE_COLOR: '1',142 DEBUG_COLORS: '1',143 MOCHA_COLORS: '1',144 FORCE_STDERR_TTY: '1',145 FORCE_STDIN_TTY: '1',146 FORCE_STDOUT_TTY: '1',147 })148 })149 })150 it('does not force colors and streams when not supported', function () {151 this.spawnedProcess.on.withArgs('close').yieldsAsync(0)152 sinon.stub(util, 'supportsColor').returns(false)153 sinon.stub(tty, 'isatty').returns(false)154 return spawn.start([], { env: {} })155 .then(() => {156 expect(cp.spawn.firstCall.args[2].env).to.deep.eq({157 FORCE_COLOR: '0',158 DEBUG_COLORS: '0',159 FORCE_STDERR_TTY: '0',160 FORCE_STDIN_TTY: '0',161 FORCE_STDOUT_TTY: '0',162 })163 })164 })165 it('pipes when on win32', function () {166 this.spawnedProcess.on.withArgs('close').yieldsAsync(0)167 os.platform.returns('win32')168 xvfb.isNeeded.returns(false)169 return spawn.start()170 .then(() => {171 expect(cp.spawn.firstCall.args[2].stdio).to.deep.eq('pipe')172 })173 })174 it('inherits when on linux and xvfb isnt needed', function () {175 this.spawnedProcess.on.withArgs('close').yieldsAsync(0)176 os.platform.returns('linux')177 xvfb.isNeeded.returns(false)178 return spawn.start()179 .then(() => {180 expect(cp.spawn.firstCall.args[2].stdio).to.deep.eq('inherit')181 })182 })183 it('uses [inherit, inherit, pipe] when linux and xvfb is needed', function () {184 this.spawnedProcess.on.withArgs('close').yieldsAsync(0)185 xvfb.isNeeded.returns(true)186 os.platform.returns('linux')187 return spawn.start()188 .then(() => {189 expect(cp.spawn.firstCall.args[2].stdio).to.deep.eq([190 'inherit', 'inherit', 'pipe',191 ])192 })193 })194 it('uses [inherit, inherit, pipe] on darwin', function () {195 this.spawnedProcess.on.withArgs('close').yieldsAsync(0)196 xvfb.isNeeded.returns(false)197 os.platform.returns('darwin')198 return spawn.start()199 .then(() => {200 expect(cp.spawn.firstCall.args[2].stdio).to.deep.eq([201 'inherit', 'inherit', 'pipe',202 ])203 })204 })205 it('writes everything on win32', function () {206 const buf1 = new Buffer('asdf')207 this.spawnedProcess.stdin.pipe.withArgs(process.stdin)208 this.spawnedProcess.stdout.pipe.withArgs(process.stdout)209 this.spawnedProcess.stderr.on210 .withArgs('data')211 .yields(buf1)212 this.spawnedProcess.on.withArgs('close').yieldsAsync(0)213 sinon.stub(process.stderr, 'write').withArgs(buf1)214 os.platform.returns('win32')215 return spawn.start()216 })217 it('does not write to process.stderr when from xlib or libudev', function () {218 const buf1 = new Buffer('Xlib: something foo')219 const buf2 = new Buffer('libudev something bar')220 const buf3 = new Buffer('asdf')221 this.spawnedProcess.stderr.on222 .withArgs('data')223 .onFirstCall()224 .yields(buf1)225 .onSecondCall()226 .yields(buf2)227 .onThirdCall()228 .yields(buf3)229 this.spawnedProcess.on.withArgs('close').yieldsAsync(0)230 sinon.stub(process.stderr, 'write').withArgs(buf3)231 os.platform.returns('linux')232 xvfb.isNeeded.returns(true)233 return spawn.start()234 .then(() => {235 expect(process.stderr.write).not.to.be.calledWith(buf1)236 expect(process.stderr.write).not.to.be.calledWith(buf2)237 })238 })239 it('does not write to process.stderr when from high sierra warnings', function () {240 const buf1 = new Buffer('2018-05-19 15:30:30.287 Cypress[7850:32145] *** WARNING: Textured Window')241 const buf2 = new Buffer('asdf')242 this.spawnedProcess.stderr.on243 .withArgs('data')244 .onFirstCall()245 .yields(buf1)246 .onSecondCall(buf2)247 .yields(buf2)248 this.spawnedProcess.on.withArgs('close').yieldsAsync(0)249 sinon.stub(process.stderr, 'write').withArgs(buf2)250 os.platform.returns('darwin')251 return spawn.start()252 .then(() => {253 expect(process.stderr.write).not.to.be.calledWith(buf1)254 })255 })256 it('catches process.stdin errors and returns when code=EPIPE', function () {257 this.spawnedProcess.on.withArgs('close').yieldsAsync(0)258 return spawn.start()259 .then(() => {260 let called = false261 const fn = () => {262 called = true263 const err = new Error()264 err.code = 'EPIPE'265 return process.stdin.emit('error', err)266 }267 expect(fn).not.to.throw()268 expect(called).to.be.true269 })270 })271 it('throws process.stdin errors code!=EPIPE', function () {272 this.spawnedProcess.on.withArgs('close').yieldsAsync(0)273 return spawn.start()274 .then(() => {275 const fn = () => {276 const err = new Error('wattttt')277 err.code = 'FAILWHALE'278 return process.stdin.emit('error', err)279 }280 expect(fn).to.throw(/wattttt/)281 })282 })283 })...
run_spec.js
Source:run_spec.js
1require('../../spec_helper')2const snapshot = require('snap-shot-it')3const util = require(`${lib}/util`)4const run = require(`${lib}/exec/run`)5const spawn = require(`${lib}/exec/spawn`)6const verify = require(`${lib}/tasks/verify`)7describe('exec run', function () {8 beforeEach(function () {9 sinon.stub(util, 'isInstalledGlobally').returns(true)10 sinon.stub(process, 'exit')11 })12 context('.processRunOptions', function () {13 it('passes --browser option', () => {14 const args = run.processRunOptions({15 browser: 'test browser',16 })17 snapshot(args)18 })19 it('passes --record option', () => {20 const args = run.processRunOptions({21 record: 'my record id',22 })23 snapshot(args)24 })25 it('does not remove --record option when using --browser', () => {26 const args = run.processRunOptions({27 record: 'foo',28 browser: 'test browser',29 })30 snapshot(args)31 })32 })33 context('.start', function () {34 beforeEach(function () {35 sinon.stub(spawn, 'start').resolves()36 sinon.stub(verify, 'start').resolves()37 })38 it('verifies cypress', function () {39 return run.start()40 .then(() => {41 expect(verify.start).to.be.calledOnce42 })43 })44 it('spawns with --key and xvfb', function () {45 return run.start({ port: '1234' })46 .then(() => {47 expect(spawn.start).to.be.calledWith(['--run-project', process.cwd(), '--port', '1234'])48 })49 })50 it('spawns with --env', function () {51 return run.start({ env: 'host=http://localhost:1337,name=brian' })52 .then(() => {53 expect(spawn.start).to.be.calledWith(['--run-project', process.cwd(), '--env', 'host=http://localhost:1337,name=brian'])54 })55 })56 it('spawns with --config', function () {57 return run.start({ config: 'watchForFileChanges=false,baseUrl=localhost' })58 .then(() => {59 expect(spawn.start).to.be.calledWith(['--run-project', process.cwd(), '--config', 'watchForFileChanges=false,baseUrl=localhost'])60 })61 })62 it('spawns with --record false', function () {63 return run.start({ record: false })64 .then(() => {65 expect(spawn.start).to.be.calledWith(['--run-project', process.cwd(), '--record', false])66 })67 })68 it('spawns with --headed true', function () {69 return run.start({ headed: true })70 .then(() => {71 expect(spawn.start).to.be.calledWith([72 '--run-project', process.cwd(), '--headed', true,73 ])74 })75 })76 it('spawns with --no-exit', function () {77 return run.start({ exit: false })78 .then(() => {79 expect(spawn.start).to.be.calledWith([80 '--run-project', process.cwd(), '--no-exit',81 ])82 })83 })84 it('spawns with --output-path', function () {85 return run.start({ outputPath: '/path/to/output' })86 .then(() => {87 expect(spawn.start).to.be.calledWith(['--run-project', process.cwd(), '--output-path', '/path/to/output'])88 })89 })90 })...
open_spec.js
Source:open_spec.js
1require('../../spec_helper')2const verify = require(`${lib}/tasks/verify`)3const spawn = require(`${lib}/exec/spawn`)4const open = require(`${lib}/exec/open`)5const util = require(`${lib}/util`)6describe('exec open', function () {7 context('.start', function () {8 beforeEach(function () {9 sinon.stub(util, 'isInstalledGlobally').returns(true)10 sinon.stub(verify, 'start').resolves()11 sinon.stub(spawn, 'start').resolves()12 })13 it('verifies download', function () {14 return open.start()15 .then(() => {16 expect(verify.start).to.be.called17 })18 })19 it('calls spawn with correct options', function () {20 return open.start({ dev: true })21 .then(() => {22 expect(spawn.start).to.be.calledWith([], {23 detached: false,24 stdio: 'inherit',25 dev: true,26 })27 })28 })29 it('spawns with port', function () {30 return open.start({ port: '1234' })31 .then(() => {32 expect(spawn.start).to.be.calledWith(['--port', '1234'])33 })34 })35 it('spawns with --env', function () {36 return open.start({ env: 'host=http://localhost:1337,name=brian' })37 .then(() => {38 expect(spawn.start).to.be.calledWith(39 ['--env', 'host=http://localhost:1337,name=brian']40 )41 })42 })43 it('spawns with --config', function () {44 return open.start({ config: 'watchForFileChanges=false,baseUrl=localhost' })45 .then(() => {46 expect(spawn.start).to.be.calledWith(47 ['--config', 'watchForFileChanges=false,baseUrl=localhost']48 )49 })50 })51 it('spawns with cwd as --project if not installed globally', function () {52 util.isInstalledGlobally.returns(false)53 return open.start()54 .then(() => {55 expect(spawn.start).to.be.calledWith(56 ['--project', process.cwd()]57 )58 })59 })60 it('spawns without --project if not installed globally and passing --global option', function () {61 util.isInstalledGlobally.returns(false)62 return open.start({ global: true })63 .then(() => {64 expect(spawn.start).not.to.be.calledWith(65 ['--project', process.cwd()]66 )67 })68 })69 it('spawns with --project passed in as options even when not installed globally', function () {70 util.isInstalledGlobally.returns(false)71 return open.start({ project: '/path/to/project' })72 .then(() => {73 expect(spawn.start).to.be.calledWith(74 ['--project', '/path/to/project']75 )76 })77 })78 it('spawns with --project if specified and installed globally', function () {79 return open.start({ project: '/path/to/project' })80 .then(() => {81 expect(spawn.start).to.be.calledWith(82 ['--project', '/path/to/project']83 )84 })85 })86 it('spawns without --project if not specified and installed globally', function () {87 return open.start()88 .then(() => {89 expect(spawn.start).to.be.calledWith([])90 })91 })92 })...
startServices.js
Source:startServices.js
1import {2 call, all, spawn, put,3} from 'redux-saga/effects';4import asyncTimeout from '~shared/utils/asyncTimeout';5import actions from '#actions';6import startAlbumsReciever from './startServices/startAblumsReciever';7import startAlbumsPublisher from './startServices/startAlbumsPublisher';8import startAlbumsSharingService from './startServices/startAlbumsSharingService';9import startDiscoverPageService from './startServices/startDiscoverPageService';10import startNotificationsService from './startServices/startNotificationsService';11import startAlbumsCollectionInfo from './startServices/startAlbumsCollectionInfo';12import startNewReleaseChecker from './startServices/startNewReleaseChecker';13import startIPFSCachingService from './startServices/startIPFSCachingService';14import startIndicatorsBarService from './startServices/startIndicatorsBarService';15function* startServices(apis) {16 yield put(actions.systemAppStartProceed(66));17 yield all([18 spawn(startAlbumsReciever, apis),19 spawn(startAlbumsPublisher, apis),20 spawn(startAlbumsSharingService, apis),21 spawn(startDiscoverPageService, apis),22 spawn(startIPFSCachingService, apis),23 spawn(startAlbumsCollectionInfo, apis),24 spawn(startNotificationsService, apis),25 spawn(startNewReleaseChecker, apis),26 spawn(startIndicatorsBarService, apis),27 ]);28 yield put(actions.systemAppStartProceed(100));29 yield call(asyncTimeout, 100);30}...
shellspawn.js
Source:shellspawn.js
1#!/usr/bin/mongod2baseName = "jstests_shellspawn";3t = db.getSiblingDB('test').getCollection( baseName );4t.drop();5if ( typeof( _startMongoProgram ) == "undefined" ){6 print( "no fork support" );7}8else {9 var evalString = "sleep( 2000 ); db.getSiblingDB('test').getCollection( '" + baseName + "' ).save( {a:1} );";10 spawn = startMongoProgramNoConnect( "mongo", "admin", "--port", myPort(), "--eval", evalString );11// assert.soon( function() { return 1 == t.count(); } );12 // SERVER-2784 debugging - error message overwritten to indicate last count value.13 assert.soon( "count = t.count(); msg = 'did not reach expected count, last value: ' + t.count(); 1 == count;" );14 15 stopMongoProgramByPid( spawn );16 17 spawn = startMongoProgramNoConnect( "mongo", "--port", myPort(), "--eval", "print( 'I am a shell' );" );18 19 stopMongoProgramByPid( spawn );20 spawn = startMongoProgramNoConnect( "mongo", "--port", myPort() );21 stopMongoProgramByPid( spawn );22 23 spawn = startMongoProgramNoConnect( "mongo", "--port", myPort() );24 25 stopMongoProgramByPid( spawn );26 // all these shells should be killed...
Using AI Code Generation
1var spawn = require('child_process').spawn;2var cypress = spawn('node_modules/.bin/cypress', ['run', '--browser', 'chrome']);3cypress.stdout.on('data', function (data) {4 console.log('stdout: ' + data);5});6cypress.stderr.on('data', function (data) {7 console.log('stderr: ' + data);8});9cypress.on('close', function (code) {10 console.log('child process exited with code ' + code);11});
Using AI Code Generation
1describe('My First Test', function() {2 it('Does not do much!', function() {3 })4})5{6 "env": {7 },8}
Using AI Code Generation
1const spawn = require('child_process').spawn;2const cypress = spawn('npm', ['run', 'cypress:run'], {3});4cypress.on('exit', function (code) {5 console.log('Child process exited with exit code ' + code);6});7const cypress = spawn('npm', ['run', 'cypress:open'], {8});9cypress.on('exit', function (code) {10 console.log('Child process exited with exit code ' + code);11});12const cypress = spawn('npm', ['run', 'cypress:run', '--', '--spec', 'cypress/integration/Example.spec.js'], {13});14cypress.on('exit', function (code) {15 console.log('Child process exited with exit code ' + code);16});17const cypress = spawn('npm', ['run', 'cypress:run', '--', '--spec', 'cypress/integration/Example.spec.js', '--browser', 'chrome'], {18});19cypress.on('exit', function (code) {20 console.log('Child process exited with exit code ' + code);21});22const cypress = spawn('npm', ['run', 'cypress:run', '--', '--spec', 'cypress/integration/Example.spec.js', '--browser', 'chrome', '--headless'], {23});24cypress.on('exit', function (code) {25 console.log('Child process exited with exit code ' + code);26});27const cypress = spawn('npm', ['run', 'cypress:run', '--', '--spec', 'cypress/integration/Example.spec.js', '--browser', 'chrome', '--headless', '--record'], {28});29cypress.on('exit', function (code) {30 console.log('Child process exited with exit code ' + code);31});
Using AI Code Generation
1const spawn = require('child_process').spawn;2describe('test', () => {3 it('test', () => {4 const ls = spawn('ls', ['-lh', '/usr']);5 ls.stdout.on('data', (data) => {6 console.log(`stdout: ${data}`);7 });8 ls.stderr.on('data', (data) => {9 console.log(`stderr: ${data}`);10 });11 ls.on('close', (code) => {12 console.log(`child process exited with code ${code}`);13 });14 });15});
Using AI Code Generation
1describe('My Test', function () {2 it('My Test Case', function () {3 cy.exec('npm run start', { failOnNonZeroExit: false })4 })5})6{7 "env": {8 }9}
Using AI Code Generation
1const spawn = require('child_process').spawn;2const ls = spawn('cypress', ['run', '--spec', 'cypress/integration/Tests/MyTest.spec.js'], { shell: true });3ls.stdout.on('data', (data) => {4 console.log(`stdout: ${data}`);5});6ls.stderr.on('data', (data) => {7 console.log(`stderr: ${data}`);8});9ls.on('close', (code) => {10 console.log(`child process exited with code ${code}`);11});
Using AI Code Generation
1const spawn = require('child_process').spawn;2const ls = spawn('cypress', ['run', '--spec', 'cypress/integration/Tests/01_Login.js'], {3});4ls.on('close', (code) => {5 console.log(`child process exited with code ${code}`);6});7ls.unref();8const spawn = require('child_process').spawn;9const ls = spawn('cypress', ['run', '--spec', 'cypress/integration/Tests/01_Login.js'], {10});11ls.on('close', (code) => {12 console.log(`child process exited with code ${code}`);13});14ls.unref();15const spawn = require('child_process').spawn;16const ls = spawn('cypress', ['run', '--spec', 'cypress/integration/Tests/01_Login.js', '--headless'], {17});18ls.on('close', (code) => {19 console.log(`child process exited with code ${code}`);20});21ls.unref();22const spawn = require('child_process').spawn;23const ls = spawn('cypress', ['run', '--spec', 'cypress/integration/Tests/01_Login.js', '--headless'], {
Using AI Code Generation
1const spawn = require("child_process").spawn;2const process = spawn("cypress", ["run", "--spec", "cypress/integration/test.js"]);3process.stdout.on("data", function(data) {4 console.log("Pipe data from child process stdout: " + data);5});6process.stderr.on("data", function(data) {7 console.log("Pipe data from child process stderr: " + data);8});9process.on("close", function(code) {10 console.log("child process exited with code " + code);11});12describe('My First Test', () => {13 it('Does not do much!', () => {14 expect(true).to.equal(true)15 })16})17cypress:cli parsed cli options {}18cypress:cli { verified: true }
Using AI Code Generation
1const spawn = require('child_process').spawn;2const cypress = spawn('node_modules/.bin/cypress', ['run', '--spec', './cypress/integration/firstTest.spec.js']);3cypress.stdout.on('data', (data) => {4 console.log('stdout:', data);5});6cypress.stderr.on('data', (data) => {7 console.log('stderr:', data);8});9cypress.on('close', (code) => {10 console.log('child process exited with code', code);11});12cypress.on('error', (err) => {13 console.log('child process error', err);14});15{16 "scripts": {17 },18 "devDependencies": {19 }20}21{22 "env": {23 },24 "reporterOptions": {25 }26}
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!!