test: promisify a bunch of tests (#16051)

* test: promisify a bunch of tests

* fix lint

* fix affinity tests

* more cowbell^Wawait

* less done
This commit is contained in:
Jeremy Apthorp 2018-12-18 22:44:03 -08:00 committed by Shelley Vohr
parent cc85946f55
commit ed3e5739dc
6 changed files with 200 additions and 265 deletions

View file

@ -13,79 +13,63 @@ describe('BrowserWindow with affinity module', () => {
const myAffinityNameUpper = 'MYAFFINITY' const myAffinityNameUpper = 'MYAFFINITY'
const anotherAffinityName = 'anotherAffinity' const anotherAffinityName = 'anotherAffinity'
function createWindowWithWebPrefs (webPrefs) { async function createWindowWithWebPrefs (webPrefs) {
return new Promise((resolve, reject) => { const w = new BrowserWindow({
const w = new BrowserWindow({ show: false,
show: false, width: 400,
width: 400, height: 400,
height: 400, webPreferences: webPrefs || {}
webPreferences: webPrefs || {}
})
w.webContents.on('did-finish-load', () => { resolve(w) })
w.loadFile(path.join(fixtures, 'api', 'blank.html'))
}) })
await w.loadFile(path.join(fixtures, 'api', 'blank.html'))
return w
} }
function testAffinityProcessIds (name, webPreferences = {}) { function testAffinityProcessIds (name, webPreferences = {}) {
describe(name, () => { describe(name, () => {
let mAffinityWindow let mAffinityWindow
before(done => { before(async () => {
createWindowWithWebPrefs({ affinity: myAffinityName, ...webPreferences }) mAffinityWindow = await createWindowWithWebPrefs({ affinity: myAffinityName, ...webPreferences })
.then((w) => {
mAffinityWindow = w
done()
})
}) })
after(done => { after(async () => {
closeWindow(mAffinityWindow, { assertSingleWindow: false }).then(() => { await closeWindow(mAffinityWindow, { assertSingleWindow: false })
mAffinityWindow = null mAffinityWindow = null
done()
})
}) })
it('should have a different process id than a default window', done => { it('should have a different process id than a default window', async () => {
createWindowWithWebPrefs({ ...webPreferences }) const w = await createWindowWithWebPrefs({ ...webPreferences })
.then(w => { const affinityID = mAffinityWindow.webContents.getOSProcessId()
const affinityID = mAffinityWindow.webContents.getOSProcessId() const wcID = w.webContents.getOSProcessId()
const wcID = w.webContents.getOSProcessId()
expect(affinityID).to.not.equal(wcID, 'Should have different OS process IDs') expect(affinityID).to.not.equal(wcID, 'Should have different OS process IDs')
closeWindow(w, { assertSingleWindow: false }).then(() => { done() }) await closeWindow(w, { assertSingleWindow: false })
})
}) })
it(`should have a different process id than a window with a different affinity '${anotherAffinityName}'`, done => { it(`should have a different process id than a window with a different affinity '${anotherAffinityName}'`, async () => {
createWindowWithWebPrefs({ affinity: anotherAffinityName, ...webPreferences }) const w = await createWindowWithWebPrefs({ affinity: anotherAffinityName, ...webPreferences })
.then(w => { const affinityID = mAffinityWindow.webContents.getOSProcessId()
const affinityID = mAffinityWindow.webContents.getOSProcessId() const wcID = w.webContents.getOSProcessId()
const wcID = w.webContents.getOSProcessId()
expect(affinityID).to.not.equal(wcID, 'Should have different OS process IDs') expect(affinityID).to.not.equal(wcID, 'Should have different OS process IDs')
closeWindow(w, { assertSingleWindow: false }).then(() => { done() }) await closeWindow(w, { assertSingleWindow: false })
})
}) })
it(`should have the same OS process id than a window with the same affinity '${myAffinityName}'`, done => { it(`should have the same OS process id than a window with the same affinity '${myAffinityName}'`, async () => {
createWindowWithWebPrefs({ affinity: myAffinityName, ...webPreferences }) const w = await createWindowWithWebPrefs({ affinity: myAffinityName, ...webPreferences })
.then(w => { const affinityID = mAffinityWindow.webContents.getOSProcessId()
const affinityID = mAffinityWindow.webContents.getOSProcessId() const wcID = w.webContents.getOSProcessId()
const wcID = w.webContents.getOSProcessId()
expect(affinityID).to.equal(wcID, 'Should have the same OS process ID') expect(affinityID).to.equal(wcID, 'Should have the same OS process ID')
closeWindow(w, { assertSingleWindow: false }).then(() => { done() }) await closeWindow(w, { assertSingleWindow: false })
})
}) })
it(`should have the same OS process id than a window with an equivalent affinity '${myAffinityNameUpper}' (case insensitive)`, done => { it(`should have the same OS process id than a window with an equivalent affinity '${myAffinityNameUpper}' (case insensitive)`, async () => {
createWindowWithWebPrefs({ affinity: myAffinityNameUpper, ...webPreferences }) const w = await createWindowWithWebPrefs({ affinity: myAffinityNameUpper, ...webPreferences })
.then(w => { const affinityID = mAffinityWindow.webContents.getOSProcessId()
const affinityID = mAffinityWindow.webContents.getOSProcessId() const wcID = w.webContents.getOSProcessId()
const wcID = w.webContents.getOSProcessId()
expect(affinityID).to.equal(wcID, 'Should have the same OS process ID') expect(affinityID).to.equal(wcID, 'Should have the same OS process ID')
closeWindow(w, { assertSingleWindow: false }).then(() => { done() }) await closeWindow(w, { assertSingleWindow: false })
})
}) })
}) })
} }
@ -114,83 +98,73 @@ describe('BrowserWindow with affinity module', () => {
}) })
} }
it('disables node integration when specified to false', done => { it('disables node integration when specified to false', async () => {
Promise.all([ const [, w] = await Promise.all([
testNodeIntegration(false), testNodeIntegration(false),
createWindowWithWebPrefs({ createWindowWithWebPrefs({
affinity: affinityWithNodeTrue, affinity: affinityWithNodeTrue,
preload, preload,
nodeIntegration: false nodeIntegration: false
}) })
]).then(args => { ])
closeWindow(args[1], { assertSingleWindow: false }).then(() => { done() }) await closeWindow(w, { assertSingleWindow: false })
})
}) })
it('disables node integration when first window is false', done => { it('disables node integration when first window is false', async () => {
Promise.all([ const [, w1] = await Promise.all([
testNodeIntegration(false), testNodeIntegration(false),
createWindowWithWebPrefs({ createWindowWithWebPrefs({
affinity: affinityWithNodeTrue, affinity: affinityWithNodeTrue,
preload, preload,
nodeIntegration: false nodeIntegration: false
}) })
]).then(args => { ])
const w1 = args[1] const [, w2] = await Promise.all([
return Promise.all([ testNodeIntegration(false),
testNodeIntegration(false), createWindowWithWebPrefs({
w1, affinity: affinityWithNodeTrue,
createWindowWithWebPrefs({ preload,
affinity: affinityWithNodeTrue, nodeIntegration: true
preload, })
nodeIntegration: true ])
}) await Promise.all([
]) closeWindow(w1, { assertSingleWindow: false }),
}).then(ws => { closeWindow(w2, { assertSingleWindow: false })
return Promise.all([ ])
closeWindow(ws[1], { assertSingleWindow: false }),
closeWindow(ws[2], { assertSingleWindow: false })
])
}).then(() => { done() })
}) })
it('enables node integration when specified to true', done => { it('enables node integration when specified to true', async () => {
Promise.all([ const [, w] = await Promise.all([
testNodeIntegration(true), testNodeIntegration(true),
createWindowWithWebPrefs({ createWindowWithWebPrefs({
affinity: affinityWithNodeFalse, affinity: affinityWithNodeFalse,
preload, preload,
nodeIntegration: true nodeIntegration: true
}) })
]).then(args => { ])
closeWindow(args[1], { assertSingleWindow: false }).then(() => { done() }) await closeWindow(w, { assertSingleWindow: false })
})
}) })
it('enables node integration when first window is true', done => { it('enables node integration when first window is true', async () => {
Promise.all([ const [, w1] = await Promise.all([
testNodeIntegration(true), testNodeIntegration(true),
createWindowWithWebPrefs({ createWindowWithWebPrefs({
affinity: affinityWithNodeFalse, affinity: affinityWithNodeFalse,
preload, preload,
nodeIntegration: true nodeIntegration: true
}) })
]).then(args => { ])
const w1 = args[1] const [, w2] = await Promise.all([
return Promise.all([ testNodeIntegration(true),
testNodeIntegration(true), createWindowWithWebPrefs({
w1, affinity: affinityWithNodeFalse,
createWindowWithWebPrefs({ preload,
affinity: affinityWithNodeFalse, nodeIntegration: false
preload, })
nodeIntegration: false ])
}) await Promise.all([
]) closeWindow(w1, { assertSingleWindow: false }),
}).then(ws => { closeWindow(w2, { assertSingleWindow: false })
return Promise.all([ ])
closeWindow(ws[1], { assertSingleWindow: false }),
closeWindow(ws[2], { assertSingleWindow: false })
])
}).then(() => { done() })
}) })
}) })
}) })

View file

@ -114,8 +114,8 @@ describe('BrowserWindow module', () => {
afterEach(closeTheWindow) afterEach(closeTheWindow)
describe('BrowserWindow constructor', () => { describe('BrowserWindow constructor', () => {
it('allows passing void 0 as the webContents', () => { it('allows passing void 0 as the webContents', async () => {
openTheWindow({ await openTheWindow({
webContents: void 0 webContents: void 0
}) })
}) })
@ -159,7 +159,7 @@ describe('BrowserWindow module', () => {
}) })
it('should emit unload handler', (done) => { it('should emit unload handler', (done) => {
w.webContents.on('did-finish-load', () => { w.close() }) w.webContents.once('did-finish-load', () => { w.close() })
w.once('closed', () => { w.once('closed', () => {
const test = path.join(fixtures, 'api', 'unload') const test = path.join(fixtures, 'api', 'unload')
const content = fs.readFileSync(test) const content = fs.readFileSync(test)
@ -171,7 +171,7 @@ describe('BrowserWindow module', () => {
}) })
it('should emit beforeunload handler', (done) => { it('should emit beforeunload handler', (done) => {
w.once('onbeforeunload', () => { done() }) w.once('onbeforeunload', () => { done() })
w.webContents.on('did-finish-load', () => { w.close() }) w.webContents.once('did-finish-load', () => { w.close() })
w.loadFile(path.join(fixtures, 'api', 'beforeunload-false.html')) w.loadFile(path.join(fixtures, 'api', 'beforeunload-false.html'))
}) })
it('should not crash when invoked synchronously inside navigation observer', (done) => { it('should not crash when invoked synchronously inside navigation observer', (done) => {
@ -292,46 +292,47 @@ describe('BrowserWindow module', () => {
describe('POST navigations', () => { describe('POST navigations', () => {
afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null) }) afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null) })
it('supports specifying POST data', (done) => { it('supports specifying POST data', async () => {
w.webContents.on('did-finish-load', () => done()) await w.loadURL(server.url, { postData: postData })
w.loadURL(server.url, { postData: postData })
}) })
it('sets the content type header on URL encoded forms', (done) => { it('sets the content type header on URL encoded forms', async () => {
w.webContents.on('did-finish-load', () => { await w.loadURL(server.url)
const requestDetails = new Promise(resolve => {
w.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => { w.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => {
assert.strictEqual(details.requestHeaders['content-type'], 'application/x-www-form-urlencoded') resolve(details)
done()
}) })
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.target = '_blank'
form.submit()
`)
}) })
w.loadURL(server.url) w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.target = '_blank'
form.submit()
`)
const details = await requestDetails
assert.strictEqual(details.requestHeaders['content-type'], 'application/x-www-form-urlencoded')
}) })
it('sets the content type header on multi part forms', (done) => { it('sets the content type header on multi part forms', async () => {
w.webContents.on('did-finish-load', () => { await w.loadURL(server.url)
const requestDetails = new Promise(resolve => {
w.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => { w.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => {
assert(details.requestHeaders['content-type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')) resolve(details)
done()
}) })
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.target = '_blank'
form.enctype = 'multipart/form-data'
file = document.createElement('input')
file.type = 'file'
file.name = 'file'
form.appendChild(file)
form.submit()
`)
}) })
w.loadURL(server.url) w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.target = '_blank'
form.enctype = 'multipart/form-data'
file = document.createElement('input')
file.type = 'file'
file.name = 'file'
form.appendChild(file)
form.submit()
`)
const details = await requestDetails
assert(details.requestHeaders['content-type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary'))
}) })
}) })
@ -1277,27 +1278,20 @@ describe('BrowserWindow module', () => {
afterEach(() => { ipcMain.removeAllListeners('answer') }) afterEach(() => { ipcMain.removeAllListeners('answer') })
describe('"preload" option', () => { describe('"preload" option', () => {
it('loads the script before other scripts in window', (done) => { it('loads the script before other scripts in window', async () => {
const preload = path.join(fixtures, 'module', 'set-global.js') const preload = path.join(fixtures, 'module', 'set-global.js')
ipcMain.once('answer', (event, test) => {
assert.strictEqual(test, 'preload')
done()
})
w.destroy() w.destroy()
w = new BrowserWindow({ w = new BrowserWindow({
show: false, show: false,
webPreferences: { webPreferences: { preload }
preload: preload
}
}) })
const p = emittedOnce(ipcMain, 'answer')
w.loadFile(path.join(fixtures, 'api', 'preload.html')) w.loadFile(path.join(fixtures, 'api', 'preload.html'))
const [, test] = await p
expect(test).to.eql('preload')
}) })
it('can successfully delete the Buffer global', (done) => { it('can successfully delete the Buffer global', async () => {
const preload = path.join(fixtures, 'module', 'delete-buffer.js') const preload = path.join(fixtures, 'module', 'delete-buffer.js')
ipcMain.once('answer', (event, test) => {
assert.strictEqual(test.toString(), 'buffer')
done()
})
w.destroy() w.destroy()
w = new BrowserWindow({ w = new BrowserWindow({
show: false, show: false,
@ -1305,15 +1299,16 @@ describe('BrowserWindow module', () => {
preload: preload preload: preload
} }
}) })
const p = emittedOnce(ipcMain, 'answer')
w.loadFile(path.join(fixtures, 'api', 'preload.html')) w.loadFile(path.join(fixtures, 'api', 'preload.html'))
const [, test] = await p
expect(test.toString()).to.eql('buffer')
}) })
it('has synchronous access to all eventual window APIs', async () => { it('has synchronous access to all eventual window APIs', async () => {
const preload = path.join(fixtures, 'module', 'access-blink-apis.js') const preload = path.join(fixtures, 'module', 'access-blink-apis.js')
const w = await openTheWindow({ const w = await openTheWindow({
show: false, show: false,
webPreferences: { webPreferences: { preload }
preload: preload
}
}) })
const p = emittedOnce(ipcMain, 'answer') const p = emittedOnce(ipcMain, 'answer')
w.loadFile(path.join(fixtures, 'api', 'preload.html')) w.loadFile(path.join(fixtures, 'api', 'preload.html'))
@ -1972,26 +1967,20 @@ describe('BrowserWindow module', () => {
} }
}) })
return new Promise((resolve, reject) => { ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', path.join(fixtures, 'api', 'window-open-preload.js'))
ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', path.join(fixtures, 'api', 'window-open-preload.js')) const p = emittedOnce(ipcMain, 'answer')
ipcMain.once('answer', (event, args, typeofProcess) => { w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'))
assert.strictEqual(args.includes('--node-integration=false'), true) const [, args, typeofProcess] = await p
assert.strictEqual(args.includes('--native-window-open'), true) expect(args).to.include('--node-integration=false')
assert.strictEqual(typeofProcess, 'undefined') expect(args).to.include('--native-window-open')
resolve() expect(typeofProcess).to.eql('undefined')
})
w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'))
})
}) })
it('should have nodeIntegration disabled in child windows', async () => { it('should have nodeIntegration disabled in child windows', async () => {
return new Promise((resolve, reject) => { const p = emittedOnce(ipcMain, 'answer')
ipcMain.once('answer', (event, typeofProcess) => { w.loadFile(path.join(fixtures, 'api', 'native-window-open-argv.html'))
assert.strictEqual(typeofProcess, 'undefined') const [, typeofProcess] = await p
resolve() expect(typeofProcess).to.eql('undefined')
})
w.loadFile(path.join(fixtures, 'api', 'native-window-open-argv.html'))
})
}) })
}) })
}) })
@ -2397,7 +2386,6 @@ describe('BrowserWindow module', () => {
let called = false let called = false
let gotInitialFullSizeFrame = false let gotInitialFullSizeFrame = false
const [contentWidth, contentHeight] = w.getContentSize() const [contentWidth, contentHeight] = w.getContentSize()
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'))
w.webContents.on('did-finish-load', () => { w.webContents.on('did-finish-load', () => {
w.webContents.beginFrameSubscription(true, (data, rect) => { w.webContents.beginFrameSubscription(true, (data, rect) => {
if (data.length === 0) { if (data.length === 0) {
@ -2426,6 +2414,7 @@ describe('BrowserWindow module', () => {
done() done()
}) })
}) })
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'))
}) })
it('throws error when subscriber is not well defined', (done) => { it('throws error when subscriber is not well defined', (done) => {
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')) w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'))
@ -2455,17 +2444,17 @@ describe('BrowserWindow module', () => {
} }
}) })
it('should save page to disk', (done) => { it('should save page to disk', async () => {
w.webContents.on('did-finish-load', () => { await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'))
const error = await new Promise(resolve => {
w.webContents.savePage(savePageHtmlPath, 'HTMLComplete', function (error) { w.webContents.savePage(savePageHtmlPath, 'HTMLComplete', function (error) {
assert.strictEqual(error, null) resolve(error)
assert(fs.existsSync(savePageHtmlPath))
assert(fs.existsSync(savePageJsPath))
assert(fs.existsSync(savePageCssPath))
done()
}) })
}) })
w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')) expect(error).to.be.null()
assert(fs.existsSync(savePageHtmlPath))
assert(fs.existsSync(savePageJsPath))
assert(fs.existsSync(savePageCssPath))
}) })
}) })
@ -3436,9 +3425,7 @@ describe('BrowserWindow module', () => {
assert.deepStrictEqual(data, expectedContextData) assert.deepStrictEqual(data, expectedContextData)
}) })
it('recreates the contexts on reload', async () => { it('recreates the contexts on reload', async () => {
const loaded = emittedOnce(iw.webContents, 'did-finish-load') await iw.loadFile(path.join(fixtures, 'api', 'isolated.html'))
iw.loadFile(path.join(fixtures, 'api', 'isolated.html'))
await loaded
const isolatedWorld = emittedOnce(ipcMain, 'isolated-world') const isolatedWorld = emittedOnce(ipcMain, 'isolated-world')
iw.webContents.reload() iw.webContents.reload()
const [, data] = await isolatedWorld const [, data] = await isolatedWorld
@ -3457,9 +3444,7 @@ describe('BrowserWindow module', () => {
assert.deepStrictEqual(data, expectedContextData) assert.deepStrictEqual(data, expectedContextData)
}) })
it('recreates the contexts on reload with sandbox on', async () => { it('recreates the contexts on reload with sandbox on', async () => {
const loaded = emittedOnce(ws.webContents, 'did-finish-load') await ws.loadFile(path.join(fixtures, 'api', 'isolated.html'))
ws.loadFile(path.join(fixtures, 'api', 'isolated.html'))
await loaded
const isolatedWorld = emittedOnce(ipcMain, 'isolated-world') const isolatedWorld = emittedOnce(ipcMain, 'isolated-world')
ws.webContents.reload() ws.webContents.reload()
const [, data] = await isolatedWorld const [, data] = await isolatedWorld

View file

@ -73,8 +73,7 @@ describe('session module', () => {
}) })
server.listen(0, '127.0.0.1', () => { server.listen(0, '127.0.0.1', () => {
const port = server.address().port const port = server.address().port
w.loadURL(`${url}:${port}`) w.webContents.once('did-finish-load', () => {
w.webContents.on('did-finish-load', () => {
w.webContents.session.cookies.get({ url }, (error, list) => { w.webContents.session.cookies.get({ url }, (error, list) => {
if (error) return done(error) if (error) return done(error)
for (let i = 0; i < list.length; i++) { for (let i = 0; i < list.length; i++) {
@ -90,6 +89,7 @@ describe('session module', () => {
done('Can\'t find cookie') done('Can\'t find cookie')
}) })
}) })
w.loadURL(`${url}:${port}`)
}) })
}) })
@ -251,7 +251,6 @@ describe('session module', () => {
assert.strictEqual(count, 0) assert.strictEqual(count, 0)
done() done()
}) })
w.loadFile(path.join(fixtures, 'api', 'localstorage.html'))
w.webContents.on('did-finish-load', () => { w.webContents.on('did-finish-load', () => {
const options = { const options = {
origin: 'file://', origin: 'file://',
@ -262,6 +261,7 @@ describe('session module', () => {
w.webContents.send('getcount') w.webContents.send('getcount')
}) })
}) })
w.loadFile(path.join(fixtures, 'api', 'localstorage.html'))
}) })
}) })
@ -388,10 +388,10 @@ describe('session module', () => {
const port = downloadServer.address().port const port = downloadServer.address().port
ipcRenderer.sendSync('set-download-option', false, false) ipcRenderer.sendSync('set-download-option', false, false)
webview = new WebView() webview = new WebView()
webview.src = `file://${fixtures}/api/blank.html`
webview.addEventListener('did-finish-load', () => { webview.addEventListener('did-finish-load', () => {
webview.downloadURL(`${url}:${port}/`) webview.downloadURL(`${url}:${port}/`)
}) })
webview.src = `file://${fixtures}/api/blank.html`
ipcRenderer.once('download-done', (event, state, url, ipcRenderer.once('download-done', (event, state, url,
mimeType, receivedBytes, mimeType, receivedBytes,
totalBytes, disposition, totalBytes, disposition,

View file

@ -279,54 +279,44 @@ describe('webContents module', () => {
}) })
describe('before-input-event event', () => { describe('before-input-event event', () => {
it('can prevent document keyboard events', (done) => { it('can prevent document keyboard events', async () => {
ipcMain.once('keydown', (event, key) => { await w.loadFile(path.join(fixtures, 'pages', 'key-events.html'))
assert.strictEqual(key, 'b') const keyDown = new Promise(resolve => {
done() ipcMain.once('keydown', (event, key) => resolve(key))
}) })
w.webContents.once('did-finish-load', () => { ipcRenderer.sendSync('prevent-next-input-event', 'a', w.webContents.id)
ipcRenderer.sendSync('prevent-next-input-event', 'a', w.webContents.id) w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' })
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' }) w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' })
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' }) assert.strictEqual(await keyDown, 'b')
})
w.loadFile(path.join(fixtures, 'pages', 'key-events.html'))
}) })
it('has the correct properties', async () => { it('has the correct properties', async () => {
await w.loadFile(path.join(fixtures, 'pages', 'base-page.html')) await w.loadFile(path.join(fixtures, 'pages', 'base-page.html'))
const testBeforeInput = (opts) => { const testBeforeInput = async (opts) => {
return new Promise((resolve, reject) => { const modifiers = []
w.webContents.once('before-input-event', (event, input) => { if (opts.shift) modifiers.push('shift')
try { if (opts.control) modifiers.push('control')
assert.strictEqual(input.type, opts.type) if (opts.alt) modifiers.push('alt')
assert.strictEqual(input.key, opts.key) if (opts.meta) modifiers.push('meta')
assert.strictEqual(input.code, opts.code) if (opts.isAutoRepeat) modifiers.push('isAutoRepeat')
assert.strictEqual(input.isAutoRepeat, opts.isAutoRepeat)
assert.strictEqual(input.shift, opts.shift)
assert.strictEqual(input.control, opts.control)
assert.strictEqual(input.alt, opts.alt)
assert.strictEqual(input.meta, opts.meta)
resolve()
} catch (e) {
reject(e)
}
})
const modifiers = [] const p = emittedOnce(w.webContents, 'before-input-event')
if (opts.shift) modifiers.push('shift') w.webContents.sendInputEvent({
if (opts.control) modifiers.push('control') type: opts.type,
if (opts.alt) modifiers.push('alt') keyCode: opts.keyCode,
if (opts.meta) modifiers.push('meta') modifiers: modifiers
if (opts.isAutoRepeat) modifiers.push('isAutoRepeat')
w.webContents.sendInputEvent({
type: opts.type,
keyCode: opts.keyCode,
modifiers: modifiers
})
}) })
} const [, input] = await p
assert.strictEqual(input.type, opts.type)
assert.strictEqual(input.key, opts.key)
assert.strictEqual(input.code, opts.code)
assert.strictEqual(input.isAutoRepeat, opts.isAutoRepeat)
assert.strictEqual(input.shift, opts.shift)
assert.strictEqual(input.control, opts.control)
assert.strictEqual(input.alt, opts.alt)
assert.strictEqual(input.meta, opts.meta)
}
await testBeforeInput({ await testBeforeInput({
type: 'keyDown', type: 'keyDown',
key: 'A', key: 'A',
@ -553,16 +543,12 @@ describe('webContents module', () => {
}) })
describe('getOSProcessId()', () => { describe('getOSProcessId()', () => {
it('returns a valid procress id', (done) => { it('returns a valid procress id', async () => {
assert.strictEqual(w.webContents.getOSProcessId(), 0) assert.strictEqual(w.webContents.getOSProcessId(), 0)
w.webContents.once('did-finish-load', () => { await w.loadURL('about:blank')
const pid = w.webContents.getOSProcessId() const pid = w.webContents.getOSProcessId()
assert.strictEqual(typeof pid, 'number') expect(pid).to.be.above(0)
assert(pid > 0, `pid ${pid} is not greater than 0`)
done()
})
w.loadURL('about:blank')
}) })
}) })
@ -595,19 +581,17 @@ describe('webContents module', () => {
protocol.unregisterProtocol(zoomScheme, (error) => done(error)) protocol.unregisterProtocol(zoomScheme, (error) => done(error))
}) })
it('can set the correct zoom level', (done) => { it('can set the correct zoom level', async () => {
w.webContents.on('did-finish-load', () => { try {
w.webContents.getZoomLevel((zoomLevel) => { await w.loadURL('about:blank')
assert.strictEqual(zoomLevel, 0.0) const zoomLevel = await new Promise(resolve => w.webContents.getZoomLevel(resolve))
w.webContents.setZoomLevel(0.5) expect(zoomLevel).to.eql(0.0)
w.webContents.getZoomLevel((zoomLevel) => { w.webContents.setZoomLevel(0.5)
assert.strictEqual(zoomLevel, 0.5) const newZoomLevel = await new Promise(resolve => w.webContents.getZoomLevel(resolve))
w.webContents.setZoomLevel(0) expect(newZoomLevel).to.eql(0.5)
done() } finally {
}) w.webContents.setZoomLevel(0)
}) }
})
w.loadURL('about:blank')
}) })
it('can persist zoom level across navigation', (done) => { it('can persist zoom level across navigation', (done) => {
@ -1148,7 +1132,7 @@ describe('webContents module', () => {
} }
}) })
it('can get printer list', (done) => { it('can get printer list', async () => {
w.destroy() w.destroy()
w = new BrowserWindow({ w = new BrowserWindow({
show: false, show: false,
@ -1156,12 +1140,9 @@ describe('webContents module', () => {
sandbox: true sandbox: true
} }
}) })
w.webContents.once('did-finish-load', () => { await w.loadURL('data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E')
const printers = w.webContents.getPrinters() const printers = w.webContents.getPrinters()
assert.strictEqual(Array.isArray(printers), true) assert.strictEqual(Array.isArray(printers), true)
done()
})
w.loadURL('data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E')
}) })
}) })

View file

@ -5,7 +5,6 @@ const path = require('path')
const { closeWindow } = require('./window-helpers') const { closeWindow } = require('./window-helpers')
const { remote, webFrame } = require('electron') const { remote, webFrame } = require('electron')
const { BrowserWindow, protocol, ipcMain } = remote const { BrowserWindow, protocol, ipcMain } = remote
const { emittedOnce } = require('./events-helpers')
const { expect } = chai const { expect } = chai
chai.use(dirtyChai) chai.use(dirtyChai)
@ -148,13 +147,12 @@ describe('webFrame module', function () {
it('calls a spellcheck provider', async () => { it('calls a spellcheck provider', async () => {
w = new BrowserWindow({ show: false }) w = new BrowserWindow({ show: false })
w.loadFile(path.join(fixtures, 'pages', 'webframe-spell-check.html')) await w.loadFile(path.join(fixtures, 'pages', 'webframe-spell-check.html'))
await emittedOnce(w.webContents, 'did-finish-load')
w.focus() w.focus()
await w.webContents.executeJavaScript('document.querySelector("input").focus()', true) await w.webContents.executeJavaScript('document.querySelector("input").focus()', true)
const spellCheckerFeedback = const spellCheckerFeedback =
new Promise((resolve, reject) => { new Promise(resolve => {
ipcMain.on('spec-spell-check', (e, words, callback) => { ipcMain.on('spec-spell-check', (e, words, callback) => {
if (words.length === 2) { if (words.length === 2) {
// The promise is resolved only after this event is received twice // The promise is resolved only after this event is received twice

View file

@ -10,7 +10,6 @@ const ChildProcess = require('child_process')
const { ipcRenderer, remote } = require('electron') const { ipcRenderer, remote } = require('electron')
const { closeWindow } = require('./window-helpers') const { closeWindow } = require('./window-helpers')
const { resolveGetters } = require('./assert-helpers') const { resolveGetters } = require('./assert-helpers')
const { emittedOnce } = require('./events-helpers')
const { app, BrowserWindow, ipcMain, protocol, session, webContents } = remote const { app, BrowserWindow, ipcMain, protocol, session, webContents } = remote
const isCI = remote.getGlobal('isCi') const isCI = remote.getGlobal('isCi')
const features = process.atomBinding('features') const features = process.atomBinding('features')
@ -1417,9 +1416,7 @@ describe('font fallback', () => {
async function getRenderedFonts (html) { async function getRenderedFonts (html) {
const w = new BrowserWindow({ show: false }) const w = new BrowserWindow({ show: false })
try { try {
const loaded = emittedOnce(w.webContents, 'did-finish-load') await w.loadURL(`data:text/html,${html}`)
w.loadURL(`data:text/html,${html}`)
await loaded
w.webContents.debugger.attach() w.webContents.debugger.attach()
const sendCommand = (...args) => new Promise((resolve, reject) => { const sendCommand = (...args) => new Promise((resolve, reject) => {
w.webContents.debugger.sendCommand(...args, (e, r) => { w.webContents.debugger.sendCommand(...args, (e, r) => {