Best JavaScript code snippet using wpt
webview-spec.js
Source:webview-spec.js
...17 for (const [name, value] of Object.entries(attributes)) {18 webview.setAttribute(name, value);19 }20 document.body.appendChild(webview);21 await waitForEvent(webview, 'did-finish-load');22 return webview;23 };24 const startLoadingWebViewAndWaitForMessage = async (webview, attributes = {}) => {25 loadWebView(webview, attributes); // Don't wait for load to be finished.26 const event = await waitForEvent(webview, 'console-message');27 return event.message;28 };29 beforeEach(() => {30 webview = new WebView();31 });32 afterEach(() => {33 if (!document.body.contains(webview)) {34 document.body.appendChild(webview);35 }36 webview.remove();37 });38 describe('src attribute', () => {39 it('specifies the page to load', async () => {40 const message = await startLoadingWebViewAndWaitForMessage(webview, {41 src: `file://${fixtures}/pages/a.html`42 });43 expect(message).to.equal('a');44 });45 it('navigates to new page when changed', async () => {46 await loadWebView(webview, {47 src: `file://${fixtures}/pages/a.html`48 });49 webview.src = `file://${fixtures}/pages/b.html`;50 const { message } = await waitForEvent(webview, 'console-message');51 expect(message).to.equal('b');52 });53 it('resolves relative URLs', async () => {54 const message = await startLoadingWebViewAndWaitForMessage(webview, {55 src: '../fixtures/pages/e.html'56 });57 expect(message).to.equal('Window script is loaded before preload script');58 });59 it('ignores empty values', () => {60 expect(webview.src).to.equal('');61 for (const emptyValue of ['', null, undefined]) {62 webview.src = emptyValue;63 expect(webview.src).to.equal('');64 }65 });66 it('does not wait until loadURL is resolved', async () => {67 await loadWebView(webview, { src: 'about:blank' });68 const before = Date.now();69 webview.src = 'https://github.com';70 const now = Date.now();71 // Setting src is essentially sending a sync IPC message, which should72 // not exceed more than a few ms.73 //74 // This is for testing #18638.75 expect(now - before).to.be.below(100);76 });77 });78 describe('nodeintegration attribute', () => {79 it('inserts no node symbols when not set', async () => {80 const message = await startLoadingWebViewAndWaitForMessage(webview, {81 src: `file://${fixtures}/pages/c.html`82 });83 const types = JSON.parse(message);84 expect(types).to.include({85 require: 'undefined',86 module: 'undefined',87 process: 'undefined',88 global: 'undefined'89 });90 });91 it('inserts node symbols when set', async () => {92 const message = await startLoadingWebViewAndWaitForMessage(webview, {93 nodeintegration: 'on',94 src: `file://${fixtures}/pages/d.html`95 });96 const types = JSON.parse(message);97 expect(types).to.include({98 require: 'function',99 module: 'object',100 process: 'object'101 });102 });103 it('loads node symbols after POST navigation when set', async function () {104 // FIXME Figure out why this is timing out on AppVeyor105 if (process.env.APPVEYOR === 'True') {106 this.skip();107 return;108 }109 const message = await startLoadingWebViewAndWaitForMessage(webview, {110 nodeintegration: 'on',111 src: `file://${fixtures}/pages/post.html`112 });113 const types = JSON.parse(message);114 expect(types).to.include({115 require: 'function',116 module: 'object',117 process: 'object'118 });119 });120 it('disables node integration on child windows when it is disabled on the webview', async () => {121 const src = url.format({122 pathname: `${fixtures}/pages/webview-opener-no-node-integration.html`,123 protocol: 'file',124 query: {125 p: `${fixtures}/pages/window-opener-node.html`126 },127 slashes: true128 });129 loadWebView(webview, {130 allowpopups: 'on',131 src132 });133 const { message } = await waitForEvent(webview, 'console-message');134 expect(JSON.parse(message).isProcessGlobalUndefined).to.be.true();135 });136 (nativeModulesEnabled ? it : it.skip)('loads native modules when navigation happens', async function () {137 await loadWebView(webview, {138 nodeintegration: 'on',139 src: `file://${fixtures}/pages/native-module.html`140 });141 webview.reload();142 const { message } = await waitForEvent(webview, 'console-message');143 expect(message).to.equal('function');144 });145 });146 describe('preload attribute', () => {147 it('loads the script before other scripts in window', async () => {148 const message = await startLoadingWebViewAndWaitForMessage(webview, {149 preload: `${fixtures}/module/preload.js`,150 src: `file://${fixtures}/pages/e.html`151 });152 expect(message).to.be.a('string');153 expect(message).to.be.not.equal('Window script is loaded before preload script');154 });155 it('preload script can still use "process" and "Buffer" when nodeintegration is off', async () => {156 const message = await startLoadingWebViewAndWaitForMessage(webview, {157 preload: `${fixtures}/module/preload-node-off.js`,158 src: `file://${fixtures}/api/blank.html`159 });160 const types = JSON.parse(message);161 expect(types).to.include({162 process: 'object',163 Buffer: 'function'164 });165 });166 it('runs in the correct scope when sandboxed', async () => {167 const message = await startLoadingWebViewAndWaitForMessage(webview, {168 preload: `${fixtures}/module/preload-context.js`,169 src: `file://${fixtures}/api/blank.html`,170 webpreferences: 'sandbox=yes'171 });172 const types = JSON.parse(message);173 expect(types).to.include({174 require: 'function', // arguments passed to it should be availale175 electron: 'undefined', // objects from the scope it is called from should not be available176 window: 'object', // the window object should be available177 localVar: 'undefined' // but local variables should not be exposed to the window178 });179 });180 it('preload script can require modules that still use "process" and "Buffer" when nodeintegration is off', async () => {181 const message = await startLoadingWebViewAndWaitForMessage(webview, {182 preload: `${fixtures}/module/preload-node-off-wrapper.js`,183 src: `file://${fixtures}/api/blank.html`184 });185 const types = JSON.parse(message);186 expect(types).to.include({187 process: 'object',188 Buffer: 'function'189 });190 });191 it('receives ipc message in preload script', async () => {192 await loadWebView(webview, {193 preload: `${fixtures}/module/preload-ipc.js`,194 src: `file://${fixtures}/pages/e.html`195 });196 const message = 'boom!';197 webview.send('ping', message);198 const { channel, args } = await waitForEvent(webview, 'ipc-message');199 expect(channel).to.equal('pong');200 expect(args).to.deep.equal([message]);201 });202 it('works without script tag in page', async () => {203 const message = await startLoadingWebViewAndWaitForMessage(webview, {204 preload: `${fixtures}/module/preload.js`,205 src: `file://${fixtures}pages/base-page.html`206 });207 const types = JSON.parse(message);208 expect(types).to.include({209 require: 'function',210 module: 'object',211 process: 'object',212 Buffer: 'function'213 });214 });215 it('resolves relative URLs', async () => {216 const message = await startLoadingWebViewAndWaitForMessage(webview, {217 preload: '../fixtures/module/preload.js',218 src: `file://${fixtures}/pages/e.html`219 });220 const types = JSON.parse(message);221 expect(types).to.include({222 require: 'function',223 module: 'object',224 process: 'object',225 Buffer: 'function'226 });227 });228 it('ignores empty values', () => {229 expect(webview.preload).to.equal('');230 for (const emptyValue of ['', null, undefined]) {231 webview.preload = emptyValue;232 expect(webview.preload).to.equal('');233 }234 });235 });236 describe('httpreferrer attribute', () => {237 it('sets the referrer url', (done) => {238 const referrer = 'http://github.com/';239 const server = http.createServer((req, res) => {240 try {241 expect(req.headers.referer).to.equal(referrer);242 done();243 } catch (e) {244 done(e);245 } finally {246 res.end();247 server.close();248 }249 }).listen(0, '127.0.0.1', () => {250 const port = server.address().port;251 loadWebView(webview, {252 httpreferrer: referrer,253 src: `http://127.0.0.1:${port}`254 });255 });256 });257 });258 describe('useragent attribute', () => {259 it('sets the user agent', async () => {260 const referrer = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko';261 const message = await startLoadingWebViewAndWaitForMessage(webview, {262 src: `file://${fixtures}/pages/useragent.html`,263 useragent: referrer264 });265 expect(message).to.equal(referrer);266 });267 });268 describe('disablewebsecurity attribute', () => {269 it('does not disable web security when not set', async () => {270 const jqueryPath = path.join(__dirname, '/static/jquery-2.0.3.min.js');271 const src = `<script src='file://${jqueryPath}'></script> <script>console.log('ok');</script>`;272 const encoded = btoa(unescape(encodeURIComponent(src)));273 const message = await startLoadingWebViewAndWaitForMessage(webview, {274 src: `data:text/html;base64,${encoded}`275 });276 expect(message).to.be.a('string');277 expect(message).to.contain('Not allowed to load local resource');278 });279 it('disables web security when set', async () => {280 const jqueryPath = path.join(__dirname, '/static/jquery-2.0.3.min.js');281 const src = `<script src='file://${jqueryPath}'></script> <script>console.log('ok');</script>`;282 const encoded = btoa(unescape(encodeURIComponent(src)));283 const message = await startLoadingWebViewAndWaitForMessage(webview, {284 disablewebsecurity: '',285 src: `data:text/html;base64,${encoded}`286 });287 expect(message).to.equal('ok');288 });289 it('does not break node integration', async () => {290 const message = await startLoadingWebViewAndWaitForMessage(webview, {291 disablewebsecurity: '',292 nodeintegration: 'on',293 src: `file://${fixtures}/pages/d.html`294 });295 const types = JSON.parse(message);296 expect(types).to.include({297 require: 'function',298 module: 'object',299 process: 'object'300 });301 });302 it('does not break preload script', async () => {303 const message = await startLoadingWebViewAndWaitForMessage(webview, {304 disablewebsecurity: '',305 preload: `${fixtures}/module/preload.js`,306 src: `file://${fixtures}/pages/e.html`307 });308 const types = JSON.parse(message);309 expect(types).to.include({310 require: 'function',311 module: 'object',312 process: 'object',313 Buffer: 'function'314 });315 });316 });317 describe('partition attribute', () => {318 it('inserts no node symbols when not set', async () => {319 const message = await startLoadingWebViewAndWaitForMessage(webview, {320 partition: 'test1',321 src: `file://${fixtures}/pages/c.html`322 });323 const types = JSON.parse(message);324 expect(types).to.include({325 require: 'undefined',326 module: 'undefined',327 process: 'undefined',328 global: 'undefined'329 });330 });331 it('inserts node symbols when set', async () => {332 const message = await startLoadingWebViewAndWaitForMessage(webview, {333 nodeintegration: 'on',334 partition: 'test2',335 src: `file://${fixtures}/pages/d.html`336 });337 const types = JSON.parse(message);338 expect(types).to.include({339 require: 'function',340 module: 'object',341 process: 'object'342 });343 });344 it('isolates storage for different id', async () => {345 window.localStorage.setItem('test', 'one');346 const message = await startLoadingWebViewAndWaitForMessage(webview, {347 partition: 'test3',348 src: `file://${fixtures}/pages/partition/one.html`349 });350 const parsedMessage = JSON.parse(message);351 expect(parsedMessage).to.include({352 numberOfEntries: 0,353 testValue: null354 });355 });356 it('uses current session storage when no id is provided', async () => {357 const testValue = 'one';358 window.localStorage.setItem('test', testValue);359 const message = await startLoadingWebViewAndWaitForMessage(webview, {360 src: `file://${fixtures}/pages/partition/one.html`361 });362 const parsedMessage = JSON.parse(message);363 expect(parsedMessage).to.include({364 numberOfEntries: 1,365 testValue366 });367 });368 });369 describe('allowpopups attribute', () => {370 const generateSpecs = (description, webpreferences = '') => {371 describe(description, () => {372 it('can not open new window when not set', async () => {373 const message = await startLoadingWebViewAndWaitForMessage(webview, {374 webpreferences,375 src: `file://${fixtures}/pages/window-open-hide.html`376 });377 expect(message).to.equal('null');378 });379 it('can open new window when set', async () => {380 const message = await startLoadingWebViewAndWaitForMessage(webview, {381 webpreferences,382 allowpopups: 'on',383 src: `file://${fixtures}/pages/window-open-hide.html`384 });385 expect(message).to.equal('window');386 });387 });388 };389 generateSpecs('without sandbox');390 generateSpecs('with sandbox', 'sandbox=yes');391 generateSpecs('with nativeWindowOpen', 'nativeWindowOpen=yes');392 });393 describe('webpreferences attribute', () => {394 it('can enable nodeintegration', async () => {395 const message = await startLoadingWebViewAndWaitForMessage(webview, {396 src: `file://${fixtures}/pages/d.html`,397 webpreferences: 'nodeIntegration'398 });399 const types = JSON.parse(message);400 expect(types).to.include({401 require: 'function',402 module: 'object',403 process: 'object'404 });405 });406 ifit(features.isRemoteModuleEnabled())('can disable the remote module', async () => {407 const message = await startLoadingWebViewAndWaitForMessage(webview, {408 preload: `${fixtures}/module/preload-disable-remote.js`,409 src: `file://${fixtures}/api/blank.html`,410 webpreferences: 'enableRemoteModule=no'411 });412 const typeOfRemote = JSON.parse(message);413 expect(typeOfRemote).to.equal('undefined');414 });415 it('can disables web security and enable nodeintegration', async () => {416 const jqueryPath = path.join(__dirname, '/static/jquery-2.0.3.min.js');417 const src = `<script src='file://${jqueryPath}'></script> <script>console.log(typeof require);</script>`;418 const encoded = btoa(unescape(encodeURIComponent(src)));419 const message = await startLoadingWebViewAndWaitForMessage(webview, {420 src: `data:text/html;base64,${encoded}`,421 webpreferences: 'webSecurity=no, nodeIntegration=yes'422 });423 expect(message).to.equal('function');424 });425 });426 describe('new-window event', () => {427 it('emits when window.open is called', async () => {428 loadWebView(webview, {429 src: `file://${fixtures}/pages/window-open.html`430 });431 const { url, frameName } = await waitForEvent(webview, 'new-window');432 expect(url).to.equal('http://host/');433 expect(frameName).to.equal('host');434 });435 it('emits when link with target is called', async () => {436 loadWebView(webview, {437 src: `file://${fixtures}/pages/target-name.html`438 });439 const { url, frameName } = await waitForEvent(webview, 'new-window');440 expect(url).to.equal('http://host/');441 expect(frameName).to.equal('target');442 });443 });444 describe('ipc-message event', () => {445 it('emits when guest sends an ipc message to browser', async () => {446 loadWebView(webview, {447 nodeintegration: 'on',448 src: `file://${fixtures}/pages/ipc-message.html`449 });450 const { channel, args } = await waitForEvent(webview, 'ipc-message');451 expect(channel).to.equal('channel');452 expect(args).to.deep.equal(['arg1', 'arg2']);453 });454 });455 describe('page-title-set event', () => {456 it('emits when title is set', async () => {457 loadWebView(webview, {458 src: `file://${fixtures}/pages/a.html`459 });460 const { title, explicitSet } = await waitForEvent(webview, 'page-title-set');461 expect(title).to.equal('test');462 expect(explicitSet).to.be.true();463 });464 });465 describe('page-favicon-updated event', () => {466 it('emits when favicon urls are received', async () => {467 loadWebView(webview, {468 src: `file://${fixtures}/pages/a.html`469 });470 const { favicons } = await waitForEvent(webview, 'page-favicon-updated');471 expect(favicons).to.be.an('array').of.length(2);472 if (process.platform === 'win32') {473 expect(favicons[0]).to.match(/^file:\/\/\/[A-Z]:\/favicon.png$/i);474 } else {475 expect(favicons[0]).to.equal('file:///favicon.png');476 }477 });478 });479 describe('will-navigate event', () => {480 it('emits when a url that leads to oustide of the page is clicked', async () => {481 loadWebView(webview, {482 src: `file://${fixtures}/pages/webview-will-navigate.html`483 });484 const { url } = await waitForEvent(webview, 'will-navigate');485 expect(url).to.equal('http://host/');486 });487 });488 describe('did-navigate event', () => {489 let p = path.join(fixtures, 'pages', 'webview-will-navigate.html');490 p = p.replace(/\\/g, '/');491 const pageUrl = url.format({492 protocol: 'file',493 slashes: true,494 pathname: p495 });496 it('emits when a url that leads to outside of the page is clicked', async () => {497 loadWebView(webview, { src: pageUrl });498 const { url } = await waitForEvent(webview, 'did-navigate');499 expect(url).to.equal(pageUrl);500 });501 });502 describe('did-navigate-in-page event', () => {503 it('emits when an anchor link is clicked', async () => {504 let p = path.join(fixtures, 'pages', 'webview-did-navigate-in-page.html');505 p = p.replace(/\\/g, '/');506 const pageUrl = url.format({507 protocol: 'file',508 slashes: true,509 pathname: p510 });511 loadWebView(webview, { src: pageUrl });512 const event = await waitForEvent(webview, 'did-navigate-in-page');513 expect(event.url).to.equal(`${pageUrl}#test_content`);514 });515 it('emits when window.history.replaceState is called', async () => {516 loadWebView(webview, {517 src: `file://${fixtures}/pages/webview-did-navigate-in-page-with-history.html`518 });519 const { url } = await waitForEvent(webview, 'did-navigate-in-page');520 expect(url).to.equal('http://host/');521 });522 it('emits when window.location.hash is changed', async () => {523 let p = path.join(fixtures, 'pages', 'webview-did-navigate-in-page-with-hash.html');524 p = p.replace(/\\/g, '/');525 const pageUrl = url.format({526 protocol: 'file',527 slashes: true,528 pathname: p529 });530 loadWebView(webview, { src: pageUrl });531 const event = await waitForEvent(webview, 'did-navigate-in-page');532 expect(event.url).to.equal(`${pageUrl}#test`);533 });534 });535 describe('close event', () => {536 it('should fire when interior page calls window.close', async () => {537 loadWebView(webview, { src: `file://${fixtures}/pages/close.html` });538 await waitForEvent(webview, 'close');539 });540 });541 // FIXME(zcbenz): Disabled because of moving to OOPIF webview.542 xdescribe('setDevToolsWebContents() API', () => {543 it('sets webContents of webview as devtools', async () => {544 const webview2 = new WebView();545 loadWebView(webview2);546 // Setup an event handler for further usage.547 const waitForDomReady = waitForEvent(webview2, 'dom-ready');548 loadWebView(webview, { src: 'about:blank' });549 await waitForEvent(webview, 'dom-ready');550 webview.getWebContents().setDevToolsWebContents(webview2.getWebContents());551 webview.getWebContents().openDevTools();552 await waitForDomReady;553 // Its WebContents should be a DevTools.554 const devtools = webview2.getWebContents();555 expect(devtools.getURL().startsWith('devtools://devtools')).to.be.true();556 const name = await devtools.executeJavaScript('InspectorFrontendHost.constructor.name');557 document.body.removeChild(webview2);558 expect(name).to.be.equal('InspectorFrontendHostImpl');559 });560 });561 describe('devtools-opened event', () => {562 it('should fire when webview.openDevTools() is called', async () => {563 loadWebView(webview, {564 src: `file://${fixtures}/pages/base-page.html`565 });566 await waitForEvent(webview, 'dom-ready');567 webview.openDevTools();568 await waitForEvent(webview, 'devtools-opened');569 webview.closeDevTools();570 });571 });572 describe('devtools-closed event', () => {573 it('should fire when webview.closeDevTools() is called', async () => {574 loadWebView(webview, {575 src: `file://${fixtures}/pages/base-page.html`576 });577 await waitForEvent(webview, 'dom-ready');578 webview.openDevTools();579 await waitForEvent(webview, 'devtools-opened');580 webview.closeDevTools();581 await waitForEvent(webview, 'devtools-closed');582 });583 });584 describe('devtools-focused event', () => {585 it('should fire when webview.openDevTools() is called', async () => {586 loadWebView(webview, {587 src: `file://${fixtures}/pages/base-page.html`588 });589 const waitForDevToolsFocused = waitForEvent(webview, 'devtools-focused');590 await waitForEvent(webview, 'dom-ready');591 webview.openDevTools();592 await waitForDevToolsFocused;593 webview.closeDevTools();594 });595 });596 describe('<webview>.reload()', () => {597 it('should emit beforeunload handler', async () => {598 await loadWebView(webview, {599 nodeintegration: 'on',600 src: `file://${fixtures}/pages/beforeunload-false.html`601 });602 // Event handler has to be added before reload.603 const waitForOnbeforeunload = waitForEvent(webview, 'ipc-message');604 webview.reload();605 const { channel } = await waitForOnbeforeunload;606 expect(channel).to.equal('onbeforeunload');607 });608 });609 describe('<webview>.goForward()', () => {610 it('should work after a replaced history entry', (done) => {611 let loadCount = 1;612 const listener = (e) => {613 if (loadCount === 1) {614 expect(e.channel).to.equal('history');615 expect(e.args[0]).to.equal(1);616 expect(webview.canGoBack()).to.be.false();617 expect(webview.canGoForward()).to.be.false();618 } else if (loadCount === 2) {619 expect(e.channel).to.equal('history');620 expect(e.args[0]).to.equal(2);621 expect(webview.canGoBack()).to.be.false();622 expect(webview.canGoForward()).to.be.true();623 webview.removeEventListener('ipc-message', listener);624 }625 };626 const loadListener = () => {627 try {628 if (loadCount === 1) {629 webview.src = `file://${fixtures}/pages/base-page.html`;630 } else if (loadCount === 2) {631 expect(webview.canGoBack()).to.be.true();632 expect(webview.canGoForward()).to.be.false();633 webview.goBack();634 } else if (loadCount === 3) {635 webview.goForward();636 } else if (loadCount === 4) {637 expect(webview.canGoBack()).to.be.true();638 expect(webview.canGoForward()).to.be.false();639 webview.removeEventListener('did-finish-load', loadListener);640 done();641 }642 loadCount += 1;643 } catch (e) {644 done(e);645 }646 };647 webview.addEventListener('ipc-message', listener);648 webview.addEventListener('did-finish-load', loadListener);649 loadWebView(webview, {650 nodeintegration: 'on',651 src: `file://${fixtures}/pages/history-replace.html`652 });653 });654 });655 // FIXME: https://github.com/electron/electron/issues/19397656 xdescribe('<webview>.clearHistory()', () => {657 it('should clear the navigation history', async () => {658 const message = waitForEvent(webview, 'ipc-message');659 await loadWebView(webview, {660 nodeintegration: 'on',661 src: `file://${fixtures}/pages/history.html`662 });663 const event = await message;664 expect(event.channel).to.equal('history');665 expect(event.args[0]).to.equal(2);666 expect(webview.canGoBack()).to.be.true();667 webview.clearHistory();668 expect(webview.canGoBack()).to.be.false();669 });670 });671 describe('basic auth', () => {672 const auth = require('basic-auth');673 it('should authenticate with correct credentials', (done) => {674 const message = 'Authenticated';675 const server = http.createServer((req, res) => {676 const credentials = auth(req);677 if (credentials.name === 'test' && credentials.pass === 'test') {678 res.end(message);679 } else {680 res.end('failed');681 }682 server.close();683 });684 server.listen(0, '127.0.0.1', () => {685 const port = server.address().port;686 webview.addEventListener('ipc-message', (e) => {687 try {688 expect(e.channel).to.equal(message);689 done();690 } catch (e) {691 done(e);692 }693 });694 loadWebView(webview, {695 nodeintegration: 'on',696 src: `file://${fixtures}/pages/basic-auth.html?port=${port}`697 });698 });699 });700 });701 describe('dom-ready event', () => {702 it('emits when document is loaded', (done) => {703 const server = http.createServer(() => {});704 server.listen(0, '127.0.0.1', () => {705 const port = server.address().port;706 webview.addEventListener('dom-ready', () => {707 done();708 });709 loadWebView(webview, {710 src: `file://${fixtures}/pages/dom-ready.html?port=${port}`711 });712 });713 });714 it('throws a custom error when an API method is called before the event is emitted', () => {715 const expectedErrorMessage =716 'The WebView must be attached to the DOM ' +717 'and the dom-ready event emitted before this method can be called.';718 expect(() => { webview.stop(); }).to.throw(expectedErrorMessage);719 });720 });721 describe('executeJavaScript', () => {722 it('should support user gesture', async () => {723 await loadWebView(webview, {724 src: `file://${fixtures}/pages/fullscreen.html`725 });726 // Event handler has to be added before js execution.727 const waitForEnterHtmlFullScreen = waitForEvent(webview, 'enter-html-full-screen');728 const jsScript = "document.querySelector('video').webkitRequestFullscreen()";729 webview.executeJavaScript(jsScript, true);730 return waitForEnterHtmlFullScreen;731 });732 it('can return the result of the executed script', async () => {733 await loadWebView(webview, {734 src: 'about:blank'735 });736 const jsScript = "'4'+2";737 const expectedResult = '42';738 const result = await webview.executeJavaScript(jsScript);739 expect(result).to.equal(expectedResult);740 });741 });742 it('supports inserting CSS', async () => {743 await loadWebView(webview, { src: `file://${fixtures}/pages/base-page.html` });744 await webview.insertCSS('body { background-repeat: round; }');745 const result = await webview.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');746 expect(result).to.equal('round');747 });748 it('supports removing inserted CSS', async () => {749 await loadWebView(webview, { src: `file://${fixtures}/pages/base-page.html` });750 const key = await webview.insertCSS('body { background-repeat: round; }');751 await webview.removeInsertedCSS(key);752 const result = await webview.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');753 expect(result).to.equal('repeat');754 });755 describe('sendInputEvent', () => {756 it('can send keyboard event', async () => {757 loadWebView(webview, {758 nodeintegration: 'on',759 src: `file://${fixtures}/pages/onkeyup.html`760 });761 await waitForEvent(webview, 'dom-ready');762 const waitForIpcMessage = waitForEvent(webview, 'ipc-message');763 webview.sendInputEvent({764 type: 'keyup',765 keyCode: 'c',766 modifiers: ['shift']767 });768 const { channel, args } = await waitForIpcMessage;769 expect(channel).to.equal('keyup');770 expect(args).to.deep.equal(['C', 'KeyC', 67, true, false]);771 });772 it('can send mouse event', async () => {773 loadWebView(webview, {774 nodeintegration: 'on',775 src: `file://${fixtures}/pages/onmouseup.html`776 });777 await waitForEvent(webview, 'dom-ready');778 const waitForIpcMessage = waitForEvent(webview, 'ipc-message');779 webview.sendInputEvent({780 type: 'mouseup',781 modifiers: ['ctrl'],782 x: 10,783 y: 20784 });785 const { channel, args } = await waitForIpcMessage;786 expect(channel).to.equal('mouseup');787 expect(args).to.deep.equal([10, 20, false, true]);788 });789 });790 describe('media-started-playing media-paused events', () => {791 it('emits when audio starts and stops playing', async () => {792 await loadWebView(webview, { src: `file://${fixtures}/pages/base-page.html` });793 // With the new autoplay policy, audio elements must be unmuted794 // see https://goo.gl/xX8pDD.795 const source = `796 const audio = document.createElement("audio")797 audio.src = "../assets/tone.wav"798 document.body.appendChild(audio);799 audio.play()800 `;801 webview.executeJavaScript(source, true);802 await waitForEvent(webview, 'media-started-playing');803 webview.executeJavaScript('document.querySelector("audio").pause()', true);804 await waitForEvent(webview, 'media-paused');805 });806 });807 describe('found-in-page event', () => {808 it('emits when a request is made', async () => {809 const didFinishLoad = waitForEvent(webview, 'did-finish-load');810 loadWebView(webview, { src: `file://${fixtures}/pages/content.html` });811 // TODO(deepak1556): With https://codereview.chromium.org/2836973002812 // focus of the webContents is required when triggering the api.813 // Remove this workaround after determining the cause for814 // incorrect focus.815 webview.focus();816 await didFinishLoad;817 const activeMatchOrdinal = [];818 for (;;) {819 const foundInPage = waitForEvent(webview, 'found-in-page');820 const requestId = webview.findInPage('virtual');821 const event = await foundInPage;822 expect(event.result.requestId).to.equal(requestId);823 expect(event.result.matches).to.equal(3);824 activeMatchOrdinal.push(event.result.activeMatchOrdinal);825 if (event.result.activeMatchOrdinal === event.result.matches) {826 break;827 }828 }829 expect(activeMatchOrdinal).to.deep.equal([1, 2, 3]);830 webview.stopFindInPage('clearSelection');831 });832 });833 describe('did-change-theme-color event', () => {834 it('emits when theme color changes', async () => {835 loadWebView(webview, {836 src: `file://${fixtures}/pages/theme-color.html`837 });838 await waitForEvent(webview, 'did-change-theme-color');839 });840 });841 describe('<webview>.getWebContentsId', () => {842 it('can return the WebContents ID', async () => {843 const src = 'about:blank';844 await loadWebView(webview, { src });845 expect(webview.getWebContentsId()).to.be.a('number');846 });847 });848 describe('<webview>.capturePage()', () => {849 before(function () {850 // TODO(miniak): figure out why this is failing on windows851 if (process.platform === 'win32') {852 this.skip();853 }854 });855 it('returns a Promise with a NativeImage', async () => {856 const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';857 await loadWebView(webview, { src });858 const image = await webview.capturePage();859 const imgBuffer = image.toPNG();860 // Check the 25th byte in the PNG.861 // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha862 expect(imgBuffer[25]).to.equal(6);863 });864 });865 ifdescribe(features.isPrintingEnabled())('<webview>.printToPDF()', () => {866 it('rejects on incorrectly typed parameters', async () => {867 const badTypes = {868 marginsType: 'terrible',869 scaleFactor: 'not-a-number',870 landscape: [],871 pageRanges: { oops: 'im-not-the-right-key' },872 headerFooter: '123',873 printSelectionOnly: 1,874 printBackground: 2,875 pageSize: 'IAmAPageSize'876 };877 // These will hard crash in Chromium unless we type-check878 for (const [key, value] of Object.entries(badTypes)) {879 const param = { [key]: value };880 const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';881 await loadWebView(webview, { src });882 await expect(webview.printToPDF(param)).to.eventually.be.rejected();883 }884 });885 it('can print to PDF', async () => {886 const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';887 await loadWebView(webview, { src });888 const data = await webview.printToPDF({});889 expect(data).to.be.an.instanceof(Uint8Array).that.is.not.empty();890 });891 });892 describe('will-attach-webview event', () => {893 it('does not emit when src is not changed', async () => {894 console.log('loadWebView(webview)');895 loadWebView(webview);896 await delay();897 const expectedErrorMessage =898 'The WebView must be attached to the DOM ' +899 'and the dom-ready event emitted before this method can be called.';900 expect(() => { webview.stop(); }).to.throw(expectedErrorMessage);901 });902 it('supports changing the web preferences', async () => {903 ipcRenderer.send('disable-node-on-next-will-attach-webview');904 const message = await startLoadingWebViewAndWaitForMessage(webview, {905 nodeintegration: 'yes',906 src: `file://${fixtures}/pages/a.html`907 });908 const types = JSON.parse(message);909 expect(types).to.include({910 require: 'undefined',911 module: 'undefined',912 process: 'undefined',913 global: 'undefined'914 });915 });916 it('supports preventing a webview from being created', async () => {917 ipcRenderer.send('prevent-next-will-attach-webview');918 loadWebView(webview, {919 src: `file://${fixtures}/pages/c.html`920 });921 await waitForEvent(webview, 'destroyed');922 });923 it('supports removing the preload script', async () => {924 ipcRenderer.send('disable-preload-on-next-will-attach-webview');925 const message = await startLoadingWebViewAndWaitForMessage(webview, {926 nodeintegration: 'yes',927 preload: path.join(fixtures, 'module', 'preload-set-global.js'),928 src: `file://${fixtures}/pages/a.html`929 });930 expect(message).to.equal('undefined');931 });932 });933 describe('DOM events', () => {934 let div;935 beforeEach(() => {936 div = document.createElement('div');937 div.style.width = '100px';938 div.style.height = '10px';939 div.style.overflow = 'hidden';940 webview.style.height = '100%';941 webview.style.width = '100%';942 });943 afterEach(() => {944 if (div != null) div.remove();945 });946 const generateSpecs = (description, sandbox) => {947 describe(description, () => {948 // TODO(nornagon): disabled during chromium roll 2019-06-11 due to a949 // 'ResizeObserver loop limit exceeded' error on Windows950 xit('emits resize events', async () => {951 const firstResizeSignal = waitForEvent(webview, 'resize');952 const domReadySignal = waitForEvent(webview, 'dom-ready');953 webview.src = `file://${fixtures}/pages/a.html`;954 webview.webpreferences = `sandbox=${sandbox ? 'yes' : 'no'}`;955 div.appendChild(webview);956 document.body.appendChild(div);957 const firstResizeEvent = await firstResizeSignal;958 expect(firstResizeEvent.target).to.equal(webview);959 expect(firstResizeEvent.newWidth).to.equal(100);960 expect(firstResizeEvent.newHeight).to.equal(10);961 await domReadySignal;962 const secondResizeSignal = waitForEvent(webview, 'resize');963 const newWidth = 1234;964 const newHeight = 789;965 div.style.width = `${newWidth}px`;966 div.style.height = `${newHeight}px`;967 const secondResizeEvent = await secondResizeSignal;968 expect(secondResizeEvent.target).to.equal(webview);969 expect(secondResizeEvent.newWidth).to.equal(newWidth);970 expect(secondResizeEvent.newHeight).to.equal(newHeight);971 });972 it('emits focus event', async () => {973 const domReadySignal = waitForEvent(webview, 'dom-ready');974 webview.src = `file://${fixtures}/pages/a.html`;975 webview.webpreferences = `sandbox=${sandbox ? 'yes' : 'no'}`;976 document.body.appendChild(webview);977 await domReadySignal;978 // If this test fails, check if webview.focus() still works.979 const focusSignal = waitForEvent(webview, 'focus');980 webview.focus();981 await focusSignal;982 });983 });984 };985 generateSpecs('without sandbox', false);986 generateSpecs('with sandbox', true);987 });...
ihlManager.js
Source:ihlManager.js
...29 guild = client.guilds.first();30 await guild.toDatabase({ captainRankThreshold: 100 });31 ihlManager = new IHLManager.IHLManager(process.env);32 await ihlManager.init(client);33 await TestHelper.waitForEvent(ihlManager)('empty');34 });35 after(async () => {36 await nockDone();37 MatchTracker.createMatchEndMessageEmbed.restore();38 DotaBot.createDotaBot.restore();39 DotaBot.loadDotaBotTickets.restore();40 });41 describe('findUser', () => {42 let member;43 beforeEach(async () => {44 member = new Mocks.MockMember(guild);45 await member.toGuild(guild).toDatabase();46 });47 it('return user matching discord id', async () => {48 const [user, discordUser, resultType] = await IHLManager.findUser(guild)(`<@${member.id}>`);49 assert.equal(user.id, 1);50 assert.equal(discordUser, member);51 assert.equal(resultType, CONSTANTS.MATCH_EXACT_DISCORD_MENTION);52 });53 it('return user matching discord id nickname', async () => {54 const [user, discordUser, resultType] = await IHLManager.findUser(guild)(`<@!${member.id}>`);55 assert.equal(user.id, 1);56 assert.equal(discordUser, member);57 assert.equal(resultType, CONSTANTS.MATCH_EXACT_DISCORD_MENTION);58 });59 it('return user matching discord name', async () => {60 const [user, discordUser, resultType] = await IHLManager.findUser(guild)(member.name);61 assert.equal(user.id, 1);62 assert.equal(discordUser.id, member.id);63 assert.equal(resultType, CONSTANTS.MATCH_EXACT_DISCORD_NAME);64 });65 });66 describe('Lobbies', () => {67 let channel;68 const selectionCommands = [69 ['First', 'First', 'Radiant'],70 ['First', 'First', 'Dire'],71 ['First', 'Second', 'Radiant'],72 ['First', 'Second', 'Dire'],73 ['First', 'Radiant', 'First'],74 ['First', 'Radiant', 'Second'],75 ['First', 'Dire', 'First'],76 ['First', 'Dire', 'Second'],77 ['Second', 'First', 'Radiant'],78 ['Second', 'First', 'Dire'],79 ['Second', 'Second', 'Radiant'],80 ['Second', 'Second', 'Dire'],81 ['Second', 'Radiant', 'First'],82 ['Second', 'Radiant', 'Second'],83 ['Second', 'Dire', 'First'],84 ['Second', 'Dire', 'Second'],85 ];86 beforeEach(async () => {87 commands = new Mocks.MockCommands(client);88 for (let i = 0; i < 10; i++) {89 const member = new Mocks.MockMember(guild);90 await member.toGuild(guild).toDatabase();91 }92 sinon.stub(DotaBot, 'startDotaLobby');93 });94 afterEach(async () => {95 DotaBot.startDotaLobby.restore();96 });97 it('autobalanced-queue', async () => {98 channel = guild.channels.find(channel => channel.name === 'autobalanced-queue');99 for (const [id, member] of guild.members) {100 if (guild.me.id !== member.id) await commands.QueueJoin({ guild, channel, member });101 }102 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_CHECKING_READY);103 for (const [id, member] of guild.members) {104 if (guild.me.id !== member.id) await commands.QueueReady({ guild, channel, member });105 }106 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_WAITING_FOR_BOT);107 DotaBot.startDotaLobby.resolves(6450130);108 await commands.BotAdd({ guild, channel, member: client.owner }, {109 steamId64: TestHelper.randomNumberString(),110 accountName: TestHelper.randomName(),111 personaName: TestHelper.randomName(),112 password: TestHelper.randomName(),113 });114 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_COMPLETED);115 await TestHelper.waitForEvent(ihlManager)('empty');116 });117 it('call onLobbyReady', async () => {118 channel = guild.channels.find(channel => channel.name === 'autobalanced-queue');119 for (const [id, member] of guild.members) {120 if (guild.me.id !== member.id) await commands.QueueJoin({ guild, channel, member });121 }122 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_CHECKING_READY);123 for (const [id, member] of guild.members) {124 if (guild.me.id !== member.id) await commands.QueueReady({ guild, channel, member });125 }126 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_WAITING_FOR_BOT);127 DotaBot.startDotaLobby.resolves(6450130);128 let dotaBot;129 ihlManager.on('bot-loaded', (bot) => {130 bot.playerState = {}; // prevent lobby from immediately starting131 dotaBot = bot;132 logger.info('bot-loaded');133 });134 await commands.BotAdd({ guild, channel, member: client.owner }, {135 steamId64: TestHelper.randomNumberString(),136 accountName: TestHelper.randomName(),137 personaName: TestHelper.randomName(),138 password: TestHelper.randomName(),139 });140 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_WAITING_FOR_PLAYERS);141 logger.info('starting lobby');142 dotaBot.playerState = dotaBot.teamCache; // make lobby ready to start143 dotaBot.emit(CONSTANTS.EVENT_LOBBY_READY);144 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_COMPLETED);145 await TestHelper.waitForEvent(ihlManager)('empty');146 });147 it('kill lobby', async () => {148 channel = guild.channels.find(channel => channel.name === 'autobalanced-queue');149 const admin = guild.members.array()[0];150 const adminRole = guild.roles.find(role => role.name === 'Inhouse Admin');151 adminRole.toGuild(guild).toMember(admin);152 for (const [id, member] of guild.members) {153 if (guild.me.id !== member.id) await commands.QueueJoin({ guild, channel, member });154 }155 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_CHECKING_READY);156 for (const [id, member] of guild.members) {157 if (guild.me.id !== member.id) await commands.QueueReady({ guild, channel, member });158 }159 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_WAITING_FOR_BOT);160 DotaBot.startDotaLobby.resolves(6450130);161 await commands.BotAdd({ guild, channel, member: client.owner }, {162 steamId64: TestHelper.randomNumberString(),163 accountName: TestHelper.randomName(),164 personaName: TestHelper.randomName(),165 password: TestHelper.randomName(),166 });167 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_WAITING_FOR_PLAYERS);168 logger.info('killing lobby');169 await commands.LobbyKill({ guild, channel, member: guild.me });170 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_KILLED);171 logger.info('killed lobby');172 await TestHelper.waitForEvent(ihlManager)('empty');173 await TestHelper.waitForEvent(ihlManager)('lobby-queue-created');174 });175 it('forward dota lobby chat message', async () => {176 channel = guild.channels.find(channel => channel.name === 'autobalanced-queue');177 for (const [id, member] of guild.members) {178 if (guild.me.id !== member.id) await commands.QueueJoin({ guild, channel, member });179 }180 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_CHECKING_READY);181 for (const [id, member] of guild.members) {182 if (guild.me.id !== member.id) await commands.QueueReady({ guild, channel, member });183 }184 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_WAITING_FOR_BOT);185 DotaBot.startDotaLobby.resolves(6450130);186 const botSteamId = TestHelper.randomNumberString();187 await commands.BotAdd({ guild, channel, member: client.owner }, {188 steamId64: botSteamId,189 accountName: TestHelper.randomName(),190 personaName: TestHelper.randomName(),191 password: TestHelper.randomName(),192 });193 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_BOT_STARTED);194 const dotaBot = await ihlManager.getBotBySteamId(botSteamId);195 const member = guild.members.array()[1];196 const user = await Db.findUserByDiscordId(guild.id)(member.id);197 dotaBot.emit(CONSTANTS.MSG_CHAT_MESSAGE, 'channel', 'Test', 'message', { account_id: convertor.to32(user.steamId64) });198 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_WAITING_FOR_PLAYERS);199 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_COMPLETED);200 await TestHelper.waitForEvent(ihlManager)('empty');201 assert.isTrue(channel.send.calledWith(`**${member.displayName}:** message`));202 });203 selectionCommands.forEach((selectionCommand) => {204 it(`player-draft-queue selection priority: ${selectionCommand.join(',')}`, async () => {205 let lobbyState;206 const captainRole = new Mocks.MockRole(guild, 'Tier 1 Captain');207 const captain1 = guild.members.array()[1];208 await captain1._model.update({ rankTier: 20 });209 const captain2 = guild.members.array()[2];210 await captain2._model.update({ rankTier: 20 });211 captainRole.toGuild(guild).toMember(captain1).toMember(captain2);212 channel = guild.channels.find(_channel => _channel.name === 'player-draft-queue');213 for (const [id, member] of guild.members) {214 if (guild.me.id !== member.id) await commands.QueueJoin({ guild, channel, member });215 }216 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_CHECKING_READY);217 for (const [id, member] of guild.members) {218 if (guild.me.id !== member.id) await commands.QueueReady({ guild, channel, member });219 }220 lobbyState = await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_SELECTION_PRIORITY);221 await commands[selectionCommand[0]]({ guild, channel, member: lobbyState.selectionPriority === 1 ? captain2 : captain1 });222 lobbyState = await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_SELECTION_PRIORITY);223 await commands[selectionCommand[1]]({ guild, channel, member: lobbyState.selectionPriority === 1 ? captain1 : captain2 });224 lobbyState = await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_SELECTION_PRIORITY);225 await commands[selectionCommand[2]]({ guild, channel, member: lobbyState.selectionPriority === 1 ? captain2 : captain1 });226 for (let i = 2; i < 10; i++) {227 lobbyState = await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_DRAFTING_PLAYERS);228 const { draftOrder } = lobbyState.inhouseState;229 const captain = ((draftOrder[i - 2] === 'A' && lobbyState.playerFirstPick === 1) || (draftOrder[i - 2] === 'B' && lobbyState.playerFirstPick === 2)) ? captain1 : captain2;230 await commands.Pick({ guild, channel, member: captain }, { member: guild.members.array()[i + 1].toMention() });231 }232 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_WAITING_FOR_BOT);233 DotaBot.startDotaLobby.resolves(6450130);234 await commands.BotAdd({ guild, channel, member: client.owner }, {235 steamId64: TestHelper.randomNumberString(),236 accountName: TestHelper.randomName(),237 personaName: TestHelper.randomName(),238 password: TestHelper.randomName(),239 });240 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_COMPLETED);241 await TestHelper.waitForEvent(ihlManager)('empty');242 });243 });244 it('challenge-queue', async () => {245 let lobbyState;246 const captain1 = guild.members.array()[1];247 const captain2 = guild.members.array()[2];248 channel = guild.channels.find(_channel => _channel.name === 'general');249 await commands.Challenge({ guild, channel, member: captain1 }, { member: captain2 });250 await commands.Challenge({ guild, channel, member: captain2 }, { member: captain1 });251 lobbyState = await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_WAITING_FOR_QUEUE);252 channel = guild.channels.find(_channel => _channel.name === lobbyState.lobbyName);253 for (let i = 2; i < 10; i++) {254 await commands.QueueJoin({ guild, channel, member: guild.members.array()[i + 1] });255 }256 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_CHECKING_READY);257 for (const [id, member] of guild.members) {258 if (guild.me.id !== member.id) await commands.QueueReady({ guild, channel, member });259 }260 lobbyState = await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_SELECTION_PRIORITY);261 await commands.First({ guild, channel, member: lobbyState.selectionPriority === 1 ? captain2 : captain1 });262 lobbyState = await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_SELECTION_PRIORITY);263 await commands.First({ guild, channel, member: lobbyState.selectionPriority === 1 ? captain1 : captain2 });264 lobbyState = await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_SELECTION_PRIORITY);265 await commands.Radiant({ guild, channel, member: lobbyState.selectionPriority === 1 ? captain2 : captain1 });266 for (let i = 2; i < 10; i++) {267 lobbyState = await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_DRAFTING_PLAYERS);268 const { draftOrder } = lobbyState.inhouseState;269 const captain = ((draftOrder[i - 2] === 'A' && lobbyState.playerFirstPick === 1) || (draftOrder[i - 2] === 'B' && lobbyState.playerFirstPick === 2)) ? captain1 : captain2;270 await commands.Pick({ guild, channel, member: captain }, { member: guild.members.array()[i + 1].toMention() });271 }272 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_WAITING_FOR_BOT);273 DotaBot.startDotaLobby.resolves(6450130);274 await commands.BotAdd({ guild, channel, member: client.owner }, {275 steamId64: TestHelper.randomNumberString(),276 accountName: TestHelper.randomName(),277 personaName: TestHelper.randomName(),278 password: TestHelper.randomName(),279 });280 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_COMPLETED);281 await TestHelper.waitForEvent(ihlManager)('empty');282 });283 it('fail ready up, complete match, requeue wrong channel, complete match', async function () {284 this.timeout(20000);285 channel = guild.channels.find(channel => channel.name === 'autobalanced-queue');286 const admin = guild.members.array()[0];287 const adminRole = guild.roles.find(role => role.name === 'Inhouse Admin');288 adminRole.toGuild(guild).toMember(admin);289 // Set ready check timeout to immediately expire.290 await commands.LeagueUpdate({ guild, channel, member: admin }, { setting: 'readyCheckTimeout', value: 0 });291 for (let i = 1; i <= 10; i++) {292 await commands.QueueJoin({ guild, channel, member: guild.members.array()[i] });293 }294 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_CHECKING_READY);295 await TestHelper.waitForEvent(ihlManager)('empty');296 logger.info('No ready up.');297 // Set ready check timeout to never expire.298 await commands.LeagueUpdate({ guild, channel, member: admin }, { setting: 'readyCheckTimeout', value: 99999 });299 for (let i = 1; i <= 10; i++) {300 await commands.QueueJoin({ guild, channel, member: guild.members.array()[i] });301 }302 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_CHECKING_READY);303 for (let i = 1; i <= 10; i++) {304 await commands.QueueReady({ guild, channel, member: guild.members.array()[i] });305 }306 logger.info('10 ready up.');307 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_WAITING_FOR_BOT);308 DotaBot.startDotaLobby.resolves(6450130);309 const botSteamId64 = TestHelper.randomNumberString();310 await commands.BotAdd({ guild, channel, member: client.owner }, {311 steamId64: botSteamId64,312 accountName: TestHelper.randomName(),313 personaName: TestHelper.randomName(),314 password: TestHelper.randomName(),315 });316 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_COMPLETED);317 await TestHelper.waitForEvent(ihlManager)('empty');318 logger.info('First match done.');319 for (let i = 1; i <= 10; i++) {320 const text = await commands.QueueJoin({ guild, channel, member: guild.members.array()[i] });321 assert.match(text, /cannot queue for this lobby/);322 }323 channel = guild.channels.find(channel => channel.name === 'autobalanced-queue');324 for (let i = 1; i <= 10; i++) {325 const text = await commands.QueueJoin({ guild, channel, member: guild.members.array()[i] });326 assert.match(text, /joined queue\. \d+ in queue/);327 }328 logger.info('10 joined queue.');329 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_CHECKING_READY);330 for (let i = 1; i <= 10; i++) {331 await commands.QueueReady({ guild, channel, member: guild.members.array()[i] });332 }333 logger.info('10 ready up.');334 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_WAITING_FOR_BOT);335 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_BOT_ASSIGNED);336 await TestHelper.waitForEvent(ihlManager)(CONSTANTS.STATE_COMPLETED);337 await TestHelper.waitForEvent(ihlManager)('empty');338 });339 340 it('rename first channel and return a new channel', async function () {341 const channelName = 'autobalanced-queue'342 channel = guild.channels.find(channel => channel.name === 'autobalanced-queue');343 const category = { id: 'category' };344 await channel.setParent(category);345 const stub = sinon.stub(Guild, 'setChannelName');346 stub.callsFake(name => async (_channel) => {347 logger.info(`FakeGuild setChannelName ${_channel.id} ${_channel.name} to ${name}`);348 const oldName = _channel.name;349 const newName = name.toLowerCase();350 if (oldName === newName) return _channel;351 return Guild.lock.acquire([`channel-${_channel.guild.id}-${oldName}`, `channel-${_channel.guild.id}-${newName}`], async () => {...
browser_context_menu_tests.js
Source:browser_context_menu_tests.js
...39 let span = win.document.getElementById("text1");40 win.getSelection().selectAllChildren(span);41 yield waitForMs(0);42 // invoke selection context menu43 let promise = waitForEvent(document, "popupshown");44 sendContextMenuClickToElement(win, span, 85, 10);45 yield promise;46 // should be visible47 ok(ContextMenuUI._menuPopup._visible, "is visible");48 // selected text context:49 checkContextUIMenuItemVisibility(["context-copy",50 "context-search"]);51 let menuItem = document.getElementById("context-copy");52 promise = waitForEvent(document, "popuphidden");53 EventUtils.synthesizeMouse(menuItem, 10, 10, {}, win);54 yield promise;55 // The wait is needed to give time to populate the clipboard.56 let string = "";57 yield waitForCondition(function () {58 string = SpecialPowers.getClipboardData("text/unicode");59 return string === span.textContent;60 });61 ok(string === span.textContent, "copied selected text from span");62 win.getSelection().removeAllRanges();63 ////////////////////////////////////////////////////////////64 // Context menu in content on selected text that includes a link65 // invoke selection with link context menu66 let link = win.document.getElementById("text2-link");67 win.getSelection().selectAllChildren(link);68 promise = waitForEvent(document, "popupshown");69 sendContextMenuClickToElement(win, link, 40, 10);70 yield promise;71 // should be visible72 ok(ContextMenuUI._menuPopup._visible, "is visible");73 // selected text context:74 checkContextUIMenuItemVisibility(["context-copy",75 "context-search",76 "context-open-in-new-tab",77 "context-copy-link"]);78 promise = waitForEvent(document, "popuphidden");79 ContextMenuUI.hide();80 yield promise;81 win.getSelection().removeAllRanges();82 ////////////////////////////////////////////////////////////83 // Context menu in content on a link84 link = win.document.getElementById("text2-link");85 promise = waitForEvent(document, "popupshown");86 sendContextMenuClickToElement(win, link, 40, 10);87 yield promise;88 // should be visible89 ok(ContextMenuUI._menuPopup._visible, "is visible");90 // selected text context:91 checkContextUIMenuItemVisibility(["context-open-in-new-tab",92 "context-copy-link",93 "context-bookmark-link"]);94 promise = waitForEvent(document, "popuphidden");95 ContextMenuUI.hide();96 yield promise;97 ////////////////////////////////////////////////////////////98 // context in input with no selection, no data on clipboard99 emptyClipboard();100 let input = win.document.getElementById("text3-input");101 promise = waitForEvent(document, "popupshown");102 sendContextMenuClickToElement(win, input, 20, 10);103 yield promise;104 // should be visible105 ok(ContextMenuUI._menuPopup._visible, "is visible");106 checkContextUIMenuItemVisibility(["context-select",107 "context-select-all"]);108 // copy menu item should not exist when no text is selected109 let menuItem = document.getElementById("context-copy");110 ok(menuItem && menuItem.hidden, "menu item is not visible");111 promise = waitForEvent(document, "popuphidden");112 ContextMenuUI.hide();113 yield promise;114 ////////////////////////////////////////////////////////////115 // context in input with selection copied to clipboard116 let input = win.document.getElementById("text3-input");117 input.value = "hello, I'm sorry but I must be going.";118 input.setSelectionRange(0, 5);119 promise = waitForEvent(document, "popupshown");120 sendContextMenuClickToElement(win, input, 20, 10);121 yield promise;122 // should be visible123 ok(ContextMenuUI._menuPopup._visible, "is visible");124 checkContextUIMenuItemVisibility(["context-cut",125 "context-copy"]);126 let menuItem = document.getElementById("context-copy");127 let popupPromise = waitForEvent(document, "popuphidden");128 EventUtils.synthesizeMouse(menuItem, 10, 10, {}, win);129 yield popupPromise;130 // The wait is needed to give time to populate the clipboard.131 let string = "";132 yield waitForCondition(function () {133 string = SpecialPowers.getClipboardData("text/unicode");134 return string === "hello";135 });136 ok(string === "hello", "copied selected text");137 emptyClipboard();138 ////////////////////////////////////////////////////////////139 // context in input with text selection, no data on clipboard140 input = win.document.getElementById("text3-input");141 input.select();142 promise = waitForEvent(document, "popupshown");143 sendContextMenuClickToElement(win, input, 20, 10);144 yield promise;145 // should be visible146 ok(ContextMenuUI._menuPopup._visible, "is visible");147 // selected text context:148 checkContextUIMenuItemVisibility(["context-cut",149 "context-copy"]);150 promise = waitForEvent(document, "popuphidden");151 ContextMenuUI.hide();152 yield promise;153 ////////////////////////////////////////////////////////////154 // context in input with no selection, data on clipboard155 SpecialPowers.clipboardCopyString("foo");156 input = win.document.getElementById("text3-input");157 input.select();158 promise = waitForEvent(document, "popupshown");159 sendContextMenuClickToElement(win, input, 20, 10);160 yield promise;161 // should be visible162 ok(ContextMenuUI._menuPopup._visible, "is visible");163 // selected text context:164 checkContextUIMenuItemVisibility(["context-cut",165 "context-copy",166 "context-paste"]);167 promise = waitForEvent(document, "popuphidden");168 ContextMenuUI.hide();169 yield promise;170 ////////////////////////////////////////////////////////////171 // context in input with selection cut to clipboard172 emptyClipboard();173 let input = win.document.getElementById("text3-input");174 input.value = "hello, I'm sorry but I must be going.";175 input.setSelectionRange(0, 5);176 promise = waitForEvent(document, "popupshown");177 sendContextMenuClickToElement(win, input, 20, 10);178 yield promise;179 // should be visible180 ok(ContextMenuUI._menuPopup._visible, "is visible");181 checkContextUIMenuItemVisibility(["context-cut",182 "context-copy"]);183 let menuItem = document.getElementById("context-cut");184 let popupPromise = waitForEvent(document, "popuphidden");185 EventUtils.synthesizeMouse(menuItem, 10, 10, {}, win);186 yield popupPromise;187 // The wait is needed to give time to populate the clipboard.188 let string = "";189 yield waitForCondition(function () {190 string = SpecialPowers.getClipboardData("text/unicode");191 return string === "hello";192 });193 let inputValue = input.value;194 ok(string === "hello", "cut selected text in clipboard");195 ok(inputValue === ", I'm sorry but I must be going.", "cut selected text from input value");196 emptyClipboard();197 ////////////////////////////////////////////////////////////198 // context in empty input, data on clipboard (paste operation)199 SpecialPowers.clipboardCopyString("foo");200 input = win.document.getElementById("text3-input");201 input.value = "";202 promise = waitForEvent(document, "popupshown");203 sendContextMenuClickToElement(win, input, 20, 10);204 yield promise;205 // should be visible206 ok(ContextMenuUI._menuPopup._visible, "is visible");207 // selected text context:208 checkContextUIMenuItemVisibility(["context-paste"]);209 promise = waitForEvent(document, "popuphidden");210 ContextMenuUI.hide();211 yield promise;212 ////////////////////////////////////////////////////////////213 // context in empty input, no data on clipboard (??)214 emptyClipboard();215 ContextUI.dismiss();216 input = win.document.getElementById("text3-input");217 input.value = "";218 promise = waitForEvent(Elements.tray, "transitionend");219 sendContextMenuClickToElement(win, input, 20, 10);220 yield promise;221 // should *not* be visible222 ok(!ContextMenuUI._menuPopup._visible, "is visible");223 // the test above will invoke the app bar224 yield hideContextUI();225 Browser.closeTab(Browser.selectedTab, { forceClose: true });226 purgeEventQueue();227 }228});229gTests.push({230 desc: "checks for context menu positioning when browser shifts",231 run: function test() {232 netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");233 info(chromeRoot + "browser_context_menu_tests_02.html");234 yield addTab(chromeRoot + "browser_context_menu_tests_02.html");235 purgeEventQueue();236 emptyClipboard();237 let browserwin = Browser.selectedTab.browser.contentWindow;238 yield hideContextUI();239 ////////////////////////////////////////////////////////////240 // test for proper context menu positioning when the browser241 // is offset by a notification box.242 yield showNotification();243 // select some text244 let span = browserwin.document.getElementById("text4");245 browserwin.getSelection().selectAllChildren(span);246 // invoke selection context menu247 let promise = waitForEvent(document, "popupshown");248 sendContextMenuClick(225, 310);249 yield promise;250 // should be visible and at a specific position251 ok(ContextMenuUI._menuPopup._visible, "is visible");252 let notificationBox = Browser.getNotificationBox();253 let notification = notificationBox.getNotificationWithValue("popup-blocked");254 let notificationHeight = notification.boxObject.height;255 checkContextMenuPositionRange(ContextMenuUI._panel, 65, 80, notificationHeight + 155, notificationHeight + 180);256 promise = waitForEvent(document, "popuphidden");257 ContextMenuUI.hide();258 yield promise;259 Browser.closeTab(Browser.selectedTab, { forceClose: true });260 }261});262var observeLogger = {263 observe: function (aSubject, aTopic, aData) {264 info("observeLogger: " + aTopic);265 },266 QueryInterface: function (aIID) {267 if (!aIID.equals(Ci.nsIObserver) &&268 !aIID.equals(Ci.nsISupportsWeakReference) &&269 !aIID.equals(Ci.nsISupports)) {270 throw Components.results.NS_ERROR_NO_INTERFACE;271 }272 return this;273 },274 init: function init() {275 Services.obs.addObserver(observeLogger, "dl-start", true);276 Services.obs.addObserver(observeLogger, "dl-done", true);277 Services.obs.addObserver(observeLogger, "dl-failed", true);278 Services.obs.addObserver(observeLogger, "dl-scanning", true);279 Services.obs.addObserver(observeLogger, "dl-blocked", true);280 Services.obs.addObserver(observeLogger, "dl-dirty", true);281 Services.obs.addObserver(observeLogger, "dl-cancel", true);282 },283 shutdown: function shutdown() {284 Services.obs.removeObserver(observeLogger, "dl-start");285 Services.obs.removeObserver(observeLogger, "dl-done");286 Services.obs.removeObserver(observeLogger, "dl-failed");287 Services.obs.removeObserver(observeLogger, "dl-scanning");288 Services.obs.removeObserver(observeLogger, "dl-blocked");289 Services.obs.removeObserver(observeLogger, "dl-dirty");290 Services.obs.removeObserver(observeLogger, "dl-cancel");291 }292}293// Image context menu tests294gTests.push({295 desc: "image context menu",296 setUp: function() {297 observeLogger.init();298 },299 tearDown: function() {300 observeLogger.shutdown();301 },302 run: function test() {303 info(chromeRoot + "browser_context_menu_tests_01.html");304 yield addTab(chromeRoot + "browser_context_menu_tests_01.html");305 let win = Browser.selectedTab.browser.contentWindow;306 purgeEventQueue();307 yield hideContextUI();308 // If we don't do this, sometimes the first sendContextMenuClickToWindow309 // will trigger the app bar.310 yield waitForImageLoad(win, "image01");311 ////////////////////////////////////////////////////////////312 // Context menu options313 // image01 - 1x1x100x100314 let promise = waitForEvent(document, "popupshown");315 sendContextMenuClickToWindow(win, 10, 10);316 yield promise;317 purgeEventQueue();318 ok(ContextMenuUI._menuPopup._visible, "is visible");319 checkContextUIMenuItemVisibility(["context-save-image-lib",320 "context-copy-image",321 "context-copy-image-loc",322 "context-open-image-tab"]);323 ////////////////////////////////////////////////////////////324 // Save to image library325 let dirSvc = Components.classes["@mozilla.org/file/directory_service;1"]326 .getService(Components.interfaces.nsIProperties);327 let saveLocationPath = dirSvc.get("Pict", Components.interfaces.nsIFile);328 saveLocationPath.append("image01.png");329 registerCleanupFunction(function () {330 saveLocationPath.remove(false);331 });332 if (saveLocationPath.exists()) {333 info("had to remove old image!");334 saveLocationPath.remove(false);335 }336 let menuItem = document.getElementById("context-save-image-lib");337 ok(menuItem, "menu item exists");338 ok(!menuItem.hidden, "menu item visible");339 // dl-start, dl-failed, dl-scanning, dl-blocked, dl-dirty, dl-cancel340 let downloadPromise = waitForObserver("dl-done", 10000);341 let popupPromise = waitForEvent(document, "popuphidden");342 EventUtils.synthesizeMouse(menuItem, 10, 10, {}, win);343 yield popupPromise;344 yield downloadPromise;345 purgeEventQueue();346 ok(saveLocationPath.exists(), "image saved");347 ////////////////////////////////////////////////////////////348 // Copy image349 let promise = waitForEvent(document, "popupshown");350 sendContextMenuClickToWindow(win, 20, 20);351 yield promise;352 ok(ContextMenuUI._menuPopup._visible, "is visible");353 menuItem = document.getElementById("context-copy-image");354 ok(menuItem, "menu item exists");355 ok(!menuItem.hidden, "menu item visible");356 popupPromise = waitForEvent(document, "popuphidden");357 EventUtils.synthesizeMouse(menuItem, 10, 10, {}, win);358 yield popupPromise;359 purgeEventQueue();360 let clip = Cc["@mozilla.org/widget/clipboard;1"].getService(Ci.nsIClipboard);361 let flavors = ["image/png"];362 ok(clip.hasDataMatchingFlavors(flavors, flavors.length, Ci.nsIClipboard.kGlobalClipboard), "clip has my png flavor");363 ////////////////////////////////////////////////////////////364 // Copy image location365 promise = waitForEvent(document, "popupshown");366 sendContextMenuClickToWindow(win, 30, 30);367 yield promise;368 ok(ContextMenuUI._menuPopup._visible, "is visible");369 menuItem = document.getElementById("context-copy-image-loc");370 ok(menuItem, "menu item exists");371 ok(!menuItem.hidden, "menu item visible");372 popupPromise = waitForEvent(document, "popuphidden");373 EventUtils.synthesizeMouse(menuItem, 10, 10, {}, win);374 yield popupPromise;375 purgeEventQueue();376 let clip = Cc["@mozilla.org/widget/clipboard;1"].getService(Ci.nsIClipboard);377 let flavors = ["text/unicode"];378 ok(clip.hasDataMatchingFlavors(flavors, flavors.length, Ci.nsIClipboard.kGlobalClipboard), "clip has my text flavor");379 let xfer = Cc["@mozilla.org/widget/transferable;1"].380 createInstance(Ci.nsITransferable);381 xfer.init(null);382 xfer.addDataFlavor("text/unicode");383 clip.getData(xfer, Ci.nsIClipboard.kGlobalClipboard);384 let str = new Object();385 let strLength = new Object();386 xfer.getTransferData("text/unicode", str, strLength);387 str = str.value.QueryInterface(Components.interfaces.nsISupportsString);388 ok(str == chromeRoot + "res/image01.png", "url copied");389 ////////////////////////////////////////////////////////////390 // Open image in new tab391 promise = waitForEvent(document, "popupshown");392 sendContextMenuClickToWindow(win, 40, 40);393 yield promise;394 ok(ContextMenuUI._menuPopup._visible, "is visible");395 menuItem = document.getElementById("context-open-image-tab");396 ok(menuItem, "menu item exists");397 ok(!menuItem.hidden, "menu item visible");398 let tabPromise = waitForEvent(document, "TabOpen");399 popupPromise = waitForEvent(document, "popuphidden");400 EventUtils.synthesizeMouse(menuItem, 10, 10, {}, win);401 yield popupPromise;402 let event = yield tabPromise;403 purgeEventQueue();404 let imagetab = Browser.getTabFromChrome(event.originalTarget);405 ok(imagetab != null, "tab created");406 Browser.closeTab(imagetab, { forceClose: true });407 }408});409gTests.push({410 desc: "tests for subframe positioning",411 run: function test() {412 info(chromeRoot + "browser_context_menu_tests_03.html");413 yield addTab(chromeRoot + "browser_context_menu_tests_03.html");414 let win = Browser.selectedTab.browser.contentWindow;415 // Sometimes the context ui is visible, sometimes it isn't.416 try {417 yield waitForCondition(function () {418 return ContextUI.isVisible;419 }, 500, 50);420 } catch (ex) {}421 ContextUI.dismiss();422 let frame1 = win.document.getElementById("frame1");423 let link1 = frame1.contentDocument.getElementById("link1");424 let promise = waitForEvent(document, "popupshown");425 sendContextMenuClickToElement(frame1.contentDocument.defaultView, link1, 85, 10);426 yield promise;427 // should be visible428 ok(ContextMenuUI._menuPopup._visible, "is visible");429 checkContextMenuPositionRange(ContextMenuUI._panel, 265, 280, 175, 190);430 promise = waitForEvent(document, "popuphidden");431 ContextMenuUI.hide();432 yield promise;433 frame1.contentDocument.defaultView.scrollBy(0, 200);434 promise = waitForEvent(document, "popupshown");435 sendContextMenuClickToElement(frame1.contentDocument.defaultView, link1, 85, 10);436 yield promise;437 // should be visible438 ok(ContextMenuUI._menuPopup._visible, "is visible");439 checkContextMenuPositionRange(ContextMenuUI._panel, 265, 280, 95, 110);440 promise = waitForEvent(document, "popuphidden");441 ContextMenuUI.hide();442 yield promise;443 let rlink1 = win.document.getElementById("rlink1");444 promise = waitForEvent(document, "popupshown");445 sendContextMenuClickToElement(win, rlink1, 40, 10);446 yield promise;447 // should be visible448 ok(ContextMenuUI._menuPopup._visible, "is visible");449 checkContextMenuPositionRange(ContextMenuUI._panel, 295, 310, 540, 555);450 promise = waitForEvent(document, "popuphidden");451 ContextMenuUI.hide();452 yield promise;453 win.scrollBy(0, 200);454 promise = waitForEvent(document, "popupshown");455 sendContextMenuClickToElement(win, rlink1, 40, 10);456 yield promise;457 // should be visible458 ok(ContextMenuUI._menuPopup._visible, "is visible");459 checkContextMenuPositionRange(ContextMenuUI._panel, 295, 310, 340, 355);460 promise = waitForEvent(document, "popuphidden");461 ContextMenuUI.hide();462 yield promise;463 let link2 = frame1.contentDocument.getElementById("link2");464 promise = waitForEvent(document, "popupshown");465 sendContextMenuClickToElement(frame1.contentDocument.defaultView, link2, 85, 10);466 yield promise;467 // should be visible468 ok(ContextMenuUI._menuPopup._visible, "is visible");469 checkContextMenuPositionRange(ContextMenuUI._panel, 265, 280, 110, 125);470 promise = waitForEvent(document, "popuphidden");471 ContextMenuUI.hide();472 yield promise;473 }474});475function test() {476 runTests();...
ad_ui_unit.js
Source:ad_ui_unit.js
...54 });55 it('becomes visible if an ad is playing', async () => {56 const eventManager = new shaka.util.EventManager();57 const waiter = new shaka.test.Waiter(eventManager);58 const p = waiter.waitForEvent(adManager, shaka.ads.AdManager.AD_STARTED);59 ad = new shaka.test.FakeAd(/* skipIn= */ null,60 /* position= */ 1, /* totalAdsInPod= */ 1);61 adManager.startAd(ad);62 await p;63 const adControlsContainer =64 UiUtils.getElementByClassName(container, 'shaka-ad-controls');65 UiUtils.confirmElementDisplayed(adControlsContainer);66 });67 it('hides when an ad is done playing', async () => {68 const eventManager = new shaka.util.EventManager();69 const waiter = new shaka.test.Waiter(eventManager);70 const pStart =71 waiter.waitForEvent(adManager, shaka.ads.AdManager.AD_STARTED);72 const pStop =73 waiter.waitForEvent(adManager, shaka.ads.AdManager.AD_STOPPED);74 ad = new shaka.test.FakeAd(/* skipIn= */ null,75 /* position= */ 1, /* totalAdsInPod= */ 1);76 adManager.startAd(ad);77 await pStart;78 const adControlsContainer =79 UiUtils.getElementByClassName(container, 'shaka-ad-controls');80 UiUtils.confirmElementDisplayed(adControlsContainer);81 adManager.finishAd();82 await pStop;83 UiUtils.confirmElementHidden(adControlsContainer);84 });85 // TODO: Skip button isn't currently used. Re-enable this suit86 // once we have other, non-IMA ad integrations.87 xdescribe('skip button', () => {88 /** @type {!HTMLButtonElement} */89 let skipButton;90 beforeEach(() => {91 skipButton =92 /** @type {!HTMLButtonElement} */ (UiUtils.getElementByClassName(93 container, 'shaka-skip-ad-button'));94 });95 it('is invisible if an unskippable ad is playing', async () => {96 const eventManager = new shaka.util.EventManager();97 const waiter = new shaka.test.Waiter(eventManager);98 const p = waiter.waitForEvent(adManager, shaka.ads.AdManager.AD_STARTED);99 ad = new shaka.test.FakeAd(/* skipIn= */ null,100 /* position= */ 1, /* totalAdsInPod= */ 1);101 adManager.startAd(ad);102 await p;103 UiUtils.confirmElementHidden(skipButton);104 });105 it('becomes visible if a skippable ad is playing', async () => {106 const eventManager = new shaka.util.EventManager();107 const waiter = new shaka.test.Waiter(eventManager);108 const p = waiter.waitForEvent(adManager, shaka.ads.AdManager.AD_STARTED);109 ad = new shaka.test.FakeAd(/* skipIn= */ 10,110 /* position= */ 1, /* totalAdsInPod= */ 1);111 adManager.startAd(ad);112 await p;113 UiUtils.confirmElementDisplayed(skipButton);114 });115 it('correctly shows the time until the ad can be skipped', async () => {116 const eventManager = new shaka.util.EventManager();117 const waiter = new shaka.test.Waiter(eventManager);118 const p = waiter.waitForEvent(adManager, shaka.ads.AdManager.AD_STARTED);119 ad = new shaka.test.FakeAd(/* skipIn= */ 10,120 /* position= */ 1, /* totalAdsInPod= */ 1);121 adManager.startAd(ad);122 await p;123 const skipCounter =124 UiUtils.getElementByClassName(container, 'shaka-skip-ad-counter');125 UiUtils.confirmElementDisplayed(skipCounter);126 expect(skipCounter.textContent).toBe('10');127 });128 it('is disabled if skip count is greater than 0', async () => {129 const eventManager = new shaka.util.EventManager();130 const waiter = new shaka.test.Waiter(eventManager);131 const p = waiter.waitForEvent(adManager, shaka.ads.AdManager.AD_STARTED);132 ad = new shaka.test.FakeAd(/* skipIn= */ 10,133 /* position= */ 1, /* totalAdsInPod= */ 1);134 adManager.startAd(ad);135 await p;136 expect(skipButton.disabled).toBe(true);137 });138 it('is enabled if an ad can be skipped now', async () => {139 const eventManager = new shaka.util.EventManager();140 const waiter = new shaka.test.Waiter(eventManager);141 const pStart =142 waiter.waitForEvent(adManager, shaka.ads.AdManager.AD_STARTED);143 const pSkip = waiter.waitForEvent(144 adManager, shaka.ads.AdManager.AD_SKIP_STATE_CHANGED);145 ad = new shaka.test.FakeAd(/* skipIn= */ 0,146 /* position= */ 1, /* totalAdsInPod= */ 1);147 adManager.startAd(ad);148 await pStart;149 adManager.changeSkipState();150 await pSkip;151 expect(skipButton.disabled).toBe(false);152 });153 it('hides skip counter if an ad can be skipped now', async () => {154 const eventManager = new shaka.util.EventManager();155 const waiter = new shaka.test.Waiter(eventManager);156 const pStart =157 waiter.waitForEvent(adManager, shaka.ads.AdManager.AD_STARTED);158 const pSkip = waiter.waitForEvent(159 adManager, shaka.ads.AdManager.AD_SKIP_STATE_CHANGED);160 ad = new shaka.test.FakeAd(/* skipIn= */ 10,161 /* position= */ 1, /* totalAdsInPod= */ 1);162 adManager.startAd(ad);163 await pStart;164 const skipCounter =165 UiUtils.getElementByClassName(container, 'shaka-skip-ad-counter');166 UiUtils.confirmElementDisplayed(skipCounter);167 // Set ad to be skippable now168 ad.setTimeUntilSkippable(0);169 adManager.changeSkipState();170 await pSkip;171 UiUtils.confirmElementHidden(skipCounter);172 });173 });174 describe('ad counter', () => {175 /** @type {!HTMLElement} */176 let adCounter;177 /** @type {!shaka.ui.Localization} */178 let localization;179 beforeEach(() => {180 adCounter = UiUtils.getElementByClassName(181 container, 'shaka-ad-counter-span');182 localization = video['ui'].getControls().getLocalization();183 });184 it('displays correct ad time', async () => {185 const eventManager = new shaka.util.EventManager();186 const waiter = new shaka.test.Waiter(eventManager);187 const p = waiter.waitForEvent(adManager, shaka.ads.AdManager.AD_STARTED);188 ad = new shaka.test.FakeAd(/* skipIn= */ null,189 /* position= */ 1, /* totalAdsInPod= */ 1);190 adManager.startAd(ad);191 ad.setRemainingTime(5); // seconds192 await p;193 // Ad counter has an internal timer that fires every 0.5 sec194 // to check the state. Give it a full second to make sure it195 // has time to catch up to the new remaining time value.196 await shaka.test.Util.delay(1);197 const expectedTimeString = '0:05 / 0:10';198 const LocIds = shaka.ui.Locales.Ids;199 const raw = localization.resolve(LocIds.AD_TIME);200 expect(adCounter.textContent).toBe(201 raw.replace('[AD_TIME]', expectedTimeString));202 });203 });204 describe('ad position', () => {205 /** @type {!HTMLElement} */206 let adPosition;207 /** @type {!shaka.ui.Localization} */208 let localization;209 beforeEach(() => {210 adPosition = UiUtils.getElementByClassName(211 container, 'shaka-ad-position-span');212 localization = video['ui'].getControls().getLocalization();213 });214 it('correctly shows "X of Y ads" for a sequence of several ads',215 async () => {216 const position = 2;217 const adsInPod = 3;218 const eventManager = new shaka.util.EventManager();219 const waiter = new shaka.test.Waiter(eventManager);220 const p = waiter.waitForEvent(221 adManager, shaka.ads.AdManager.AD_STARTED);222 ad = new shaka.test.FakeAd(/* skipIn= */ null,223 /* position= */ position, /* totalAdsInPod= */ adsInPod);224 adManager.startAd(ad);225 await p;226 const LocIds = shaka.ui.Locales.Ids;227 const expectedString = localization.resolve(LocIds.AD_PROGRESS)228 .replace('[AD_ON]', String(position))229 .replace('[NUM_ADS]', String(adsInPod));230 expect(adPosition.textContent).toBe(expectedString);231 });232 });233 describe('timeline', () => {234 /** @type {!HTMLElement} */235 let seekBar;236 /** @type {!HTMLElement} */237 let adMarkersBar;238 beforeEach(() => {239 seekBar = UiUtils.getElementByClassName(240 container, 'shaka-seek-bar-container');241 adMarkersBar = UiUtils.getElementByClassName(242 container, 'shaka-ad-markers');243 });244 it('dissappears when an ad is playing', async () => {245 const eventManager = new shaka.util.EventManager();246 const waiter = new shaka.test.Waiter(eventManager);247 const p = waiter.waitForEvent(adManager, shaka.ads.AdManager.AD_STARTED);248 ad = new shaka.test.FakeAd(/* skipIn= */ null,249 /* position= */ 1, /* totalAdsInPod= */ 1);250 adManager.startAd(ad);251 await p;252 UiUtils.confirmElementHidden(seekBar);253 });254 it('ad markers aren\'t displayed if there are no ads', () => {255 expect(adMarkersBar.style.background).toBe('');256 });257 });258 describe('overflow menu', () => {259 /** @type {!HTMLElement} */260 let overflowMenuButton;261 beforeEach(() => {262 overflowMenuButton = UiUtils.getElementByClassName(263 container, 'shaka-overflow-menu-button');264 });265 it('is hidden when an ad is playing', async () => {266 const eventManager = new shaka.util.EventManager();267 const waiter = new shaka.test.Waiter(eventManager);268 const p = waiter.waitForEvent(adManager, shaka.ads.AdManager.AD_STARTED);269 ad = new shaka.test.FakeAd(/* skipIn= */ null,270 /* position= */ 1, /* totalAdsInPod= */ 1);271 adManager.startAd(ad);272 await p;273 UiUtils.confirmElementHidden(overflowMenuButton);274 });275 it('is displayed when an ad stops playing', async () => {276 const eventManager = new shaka.util.EventManager();277 const waiter = new shaka.test.Waiter(eventManager);278 const pStart =279 waiter.waitForEvent(adManager, shaka.ads.AdManager.AD_STARTED);280 const pStop =281 waiter.waitForEvent(adManager, shaka.ads.AdManager.AD_STOPPED);282 ad = new shaka.test.FakeAd(/* skipIn= */ null,283 /* position= */ 1, /* totalAdsInPod= */ 1);284 adManager.startAd(ad);285 await pStart;286 UiUtils.confirmElementHidden(overflowMenuButton);287 adManager.finishAd();288 await pStop;289 UiUtils.confirmElementDisplayed(overflowMenuButton);290 });291 });...
filereader_test.js
Source:filereader_test.js
...163}164function waitForAsync(msg) {165 asyncTestCase.waitForAsync(msg);166}167function waitForEvent(type, target) {168 var d = new goog.async.Deferred();169 goog.events.listenOnce(target, type, goog.bind(d.callback, d, target));170 return d;171}172function waitForError(type, target) {173 var d = new goog.async.Deferred();174 goog.events.listenOnce(175 target, goog.fs.FileReader.EventType.ERROR, function(e) {176 assertEquals(type, target.getError().code);177 d.callback(target);178 });179 return d;180}181function readAsText(reader) {182 reader.readAsText(file);183}184function readAsArrayBuffer(reader) {185 reader.readAsArrayBuffer(file);186}187function readAsDataUrl(reader) {188 reader.readAsDataUrl(file);189}190function readAndWait(reader) {191 readAsText(reader);192 return waitForEvent(goog.fs.FileSaver.EventType.LOAD_END, reader);193}194function checkResult(expectedResult, reader) {195 checkEquals(expectedResult, reader.getResult());196}197function checkEquals(a, b) {198 if (hasArrayBuffer &&199 a instanceof ArrayBuffer && b instanceof ArrayBuffer) {200 assertEquals(a.byteLength, b.byteLength);201 var viewA = new Uint8Array(a);202 var viewB = new Uint8Array(b);203 for (var i = 0; i < a.byteLength; i++) {204 assertEquals(viewA[i], viewB[i]);205 }206 } else {...
branches_select_spec.js
Source:branches_select_spec.js
...49 expect(select2Container()).not.toBe(null);50 });51 it('displays all the protected branches and any branch', done => {52 createComponent();53 waitForEvent($input, 'select2-loaded')54 .then(() => {55 const nodeList = select2DropdownOptions();56 const names = [...nodeList].map(el => el.textContent);57 expect(names).toEqual(branchNames());58 })59 .then(done)60 .catch(done.fail);61 search();62 });63 describe('with search term', () => {64 beforeEach(() => {65 createComponent();66 });67 it('fetches protected branches with search term', done => {68 const term = 'lorem';69 waitForEvent($input, 'select2-loaded')70 .then(() => {})71 .then(done)72 .catch(done.fail);73 search(term);74 expect(Api.projectProtectedBranches).toHaveBeenCalledWith(TEST_PROJECT_ID, term);75 });76 it('fetches protected branches with no any branch if there is search', done => {77 waitForEvent($input, 'select2-loaded')78 .then(() => {79 const nodeList = select2DropdownOptions();80 const names = [...nodeList].map(el => el.textContent);81 expect(names).toEqual(protectedBranchNames());82 })83 .then(done)84 .catch(done.fail);85 search('master');86 });87 it('fetches protected branches with any branch if search contains term "any"', done => {88 waitForEvent($input, 'select2-loaded')89 .then(() => {90 const nodeList = select2DropdownOptions();91 const names = [...nodeList].map(el => el.textContent);92 expect(names).toEqual(branchNames());93 })94 .then(done)95 .catch(done.fail);96 search('any');97 });98 });99 it('emits input when data changes', done => {100 createComponent();101 const selectedIndex = 1;102 const selectedId = TEST_BRANCHES_SELECTIONS[selectedIndex].id;103 const expected = [104 {105 name: 'input',106 args: [selectedId],107 },108 ];109 waitForEvent($input, 'select2-loaded')110 .then(() => {111 const options = select2DropdownOptions();112 $(options[selectedIndex]).trigger('mouseup');113 })114 .then(done)115 .catch(done.fail);116 waitForEvent($input, 'change')117 .then(() => {118 expect(wrapper.emittedByOrder()).toEqual(expected);119 })120 .then(done)121 .catch(done.fail);122 search();123 });...
media-fullscreen.js
Source:media-fullscreen.js
...81 mediaElement.load();82}83function addEventListeners(elem)84{85 waitForEvent("error");86 waitForEvent("loadstart");87 waitForEvent("waiting");88 waitForEvent("ratechange");89 waitForEvent("durationchange");90 waitForEvent("pause");91 waitForEvent("play");92 waitForEvent("playing");93 waitForEvent('canplaythrough', canplaythrough);94 waitForEvent('webkitbeginfullscreen', beginfullscreen);95 waitForEvent('webkitendfullscreen', endfullscreen);...
functions_77.js
Source:functions_77.js
1var searchData=2[3 ['waitfordelegate',['WaitForDelegate',['../class_otter_1_1_coroutine.html#a6d54849e02a10bed8eda11f72dce1699',1,'Otter::Coroutine']]],4 ['waitforevent',['WaitForEvent',['../class_otter_1_1_coroutine.html#ae3384c29ad52b1b185fb99802bd9e261',1,'Otter.Coroutine.WaitForEvent(string id)'],['../class_otter_1_1_coroutine.html#a20f552d9b7c0ea4b85d98b1e81cc8b62',1,'Otter.Coroutine.WaitForEvent(Enum id)']]],5 ['waitforframes',['WaitForFrames',['../class_otter_1_1_coroutine.html#a6f57f0a890eb24262b8b0db154baa5c7',1,'Otter::Coroutine']]],6 ['waitforseconds',['WaitForSeconds',['../class_otter_1_1_coroutine.html#a310bcd2ca7e428872fbf2e2bba7870e3',1,'Otter::Coroutine']]],7 ['waitfortween',['WaitForTween',['../class_otter_1_1_coroutine.html#a3ee6941e4b827f06f1162c82cff40653',1,'Otter::Coroutine']]],8 ['watch',['Watch',['../class_otter_1_1_debugger.html#a603b34f82350e8c77864221bd896abcf',1,'Otter::Debugger']]]...
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.runTest(url, function(err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log('Test ID: ' + data.data.testId);8 wpt.waitForTestComplete(data.data.testId, function(err, data) {9 if (err) {10 console.log(err);11 } else {12 console.log(data);13 }14 });15 }16});
Using AI Code Generation
1var wpt = require('wpt.js');2var wpt = new WebPagetest('www.webpagetest.org');3 if (err) {4 console.log(err);5 } else {6 wpt.waitForTestComplete(data.data.testId, 60, function(err, data) {7 if (err) {8 console.log(err);9 } else {10 console.log(data);11 }12 });13 }14});15#### new WebPagetest(apiKey, host, port, https)16#### runTest(url, options, callback)17#### getTestStatus(testId, callback)18#### getLocations(callback)19#### getTesters(callback)20#### getTestResults(testId, callback)21#### getTestResultsByUrl(url, callback)22#### getTestResultsByLocation(url, location, callback)
Using AI Code Generation
1var wptools = require('wptools');2var page = wptools.page('Barack_Obama');3page.waitForEvent('ready', function(err, resp) {4 console.log(resp);5});6### waitForEvent(event, callback, [timeout])7var wptools = require('wptools');8var page = wptools.page('Barack_Obama');9page.waitForEvent('ready').then(function(resp) {10 console.log(resp);11});12### waitForSelector(selector, [timeout])13var wptools = require('wptools');14var page = wptools.page('Barack_Obama');15page.waitForSelector('.firstHeading').then(function() {16 console.log('Found first heading');17});18### waitForSelectorAll(selector, [timeout])19var wptools = require('wptools');20var page = wptools.page('Barack_Obama');21page.waitForSelectorAll('a').then(function(links) {22 console.log('Found ' + links.length + ' links');23});24### waitForText(selector, text, [timeout])25var wptools = require('wptools');26var page = wptools.page('Barack_Obama');27page.waitForText('.firstHeading
Using AI Code Generation
1var wptools = require('wptools');2var wp = new wptools('Barack_Obama');3wp.waitForEvent('page.ready', function(err, data) {4 console.log(data);5});6var wptools = require('wptools');7var wp = new wptools('Barack_Obama');8wp.waitForEvent('page.ready', function(err, data) {9 console.log(data);10});11var wptools = require('wptools');12var wp = new wptools('Barack_Obama');13wp.waitForEvent('page.ready', function(err, data) {14 console.log(data);15});16var wptools = require('wptools');17var wp = new wptools('Barack_Obama');18wp.waitForEvent('page.ready', function(err, data) {19 console.log(data);20});21var wptools = require('wptools');22var wp = new wptools('Barack_Obama');23wp.waitForEvent('page.ready', function(err, data) {24 console.log(data);25});26var wptools = require('wptools');27var wp = new wptools('Barack_Obama');28wp.waitForEvent('page.ready', function(err, data) {29 console.log(data);30});31var wptools = require('wptools');32var wp = new wptools('Barack_Obama');33wp.waitForEvent('page.ready', function(err, data) {34 console.log(data);35});
Using AI Code Generation
1var wptools = require('wp-tools');2wptools.waitForEvent('test', 'testEvent', 5000, function (err, data) {3 console.log('Test event received');4});5wptools.emitEvent('test', 'testEvent', {6});7var wptools = require('wp-tools');8wptools.waitForEvent('test', 'testEvent', 5000, function (err, data) {9 console.log('Test event received');10});11wptools.emitEvent('test', 'testEvent', {12});
Using AI Code Generation
1wptutils.waitForEvent(window, "load", function() {2});3wptutils.waitForEvent(window, "load", function() {4});5wptutils.waitForEvent(window, "load", function() {6});7wptutils.waitForEvent(window, "load", function() {8});9wptutils.waitForEvent(window, "load", function() {10});11wptutils.waitForEvent(window, "load", function() {12});13wptutils.waitForEvent(window, "load", function() {14});15wptutils.waitForEvent(window, "load", function() {16});
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.waitForTest('170515_1Y_8b8e7a39c6d3f3c3b3f3ebd3c0a2a9b4', function(err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});10{statusCode: 200,11data: {statusCode: 200,12data: {statusCode:
Using AI Code Generation
1waitForEvent("onload", 1000, function(data){2 console.log(data);3}, function(eventData){4 return eventData.data == "hello";5});6waitForEvent("onload", 1000, function(data){7 console.log(data);8}, function(eventData){9 return eventData.data == "hello";10});11waitForEvent("onload", 1000, function(data){12 console.log(data);13}, function(eventData){14 return eventData.data == "hello";15});16waitForEvent("onload", 1000, function(data){17 console.log(data);18}, function(eventData){19 return eventData.data == "hello";20});
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!!