Skip to content

When calling waitUntilWindowLoaded, webContents is not set in Application #174

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
burdeasa opened this issue Mar 22, 2017 · 26 comments · May be fixed by #226
Closed

When calling waitUntilWindowLoaded, webContents is not set in Application #174

burdeasa opened this issue Mar 22, 2017 · 26 comments · May be fixed by #226

Comments

@burdeasa
Copy link

I'm seeing:
waitUntilWindowLoaded: Cannot read property 'isLoading' of undefined

This is the same issue as reported in issue 157, but that was closed, so I thought I would open a new issue.
See: #157

I am using spectron 3.4.0 with electron 1.3.2, but I also tried spectron 3.3.0 and this made no difference for me.

After running a lot of tests and debugging, I am pretty convinced the issue is related to the following:

It appears that things work fine as long as the electron App under test creates AND loads its window immediately upon call to the app ready event handler. However, if loading the window is deferred to perform some other processing first, the above error occurs consistently.

Just to be real clear here:

The following does not seem to have a problem:

let mainWindow

app.on('ready', () => {
    mainWindow = new BrowserWindow({ 
        width: 1400, 
        height: 900,
        backgroundColor: '#EAECEE'
    })
    mainWindow.loadURL(`file://${__dirname}/index.html`)
})

However, the following always seems to fail:

let mainWindow

app.on('ready', () => {
    mainWindow = new BrowserWindow({ 
        width: 1400, 
        height: 900,
        backgroundColor: '#EAECEE'
    })
    setTimeout(() => {
        mainWindow.loadURL(`file://${__dirname}/index.html`)
    }, 2000)
})
@samvloeberghs
Copy link

having related issues..

@Sigurthorb
Copy link

Sigurthorb commented Jun 12, 2017

I am also having the same issue.
Doing a syncronous call to the fs before loading the file also produces this error:

app.on('ready', () => {
    window = new BrowserWindow({ 
        width: 1400, 
        height: 900,
        backgroundColor: '#EAECEE'
    });

    if (fs.existsSync(path.join(process.cwd(), 'index.html'))) {
        window.loadURL(`file://${process.cwd()}/index.html`);
    } else {
        window.loadURL(`file://${process.cwd()}/some/other/path/index.html`);
    }
});

@stepbeta
Copy link

stepbeta commented Jul 19, 2017

Having the same issue too. I'm using electron 1.6.11 and tried with both spectron 3.7.2 and 3.6.4, but the issue is the same.

The code I run is the following:

import { expect } from 'chai';
import { Application } from 'spectron';

const timeout = 10000;

describe('application launch', function () {
    let app;

    const startApp = function() {
        app = new Application({
            path: require('electron'),
            args: ['src/init'],
            startTimeout: timeout,
            waitTimeout: timeout,
        });
        return app.start().then(setupApp);
    };

    const setupApp = function() {
        return app.client.waitUntilWindowLoaded();
    };

    before(function() {
        this.timeout(timeout);
        return startApp();
    });

    after(function () {
        if (app && app.isRunning()) {
            return app.stop();
        }
    });

    it('shows hello world text on screen after launch', function () {
        return app.client.element('#title').then(function (text) {
            expect(text).to.equal('Hello world');
        });
    });
});

If I skip the setupApp function, then text is an object:

{
  message: "An element could not be located on the page using the given search parameters.",
  selector: "#title",
  sessionId: "aa61e928c97596416a08b4c89b51dea4",
  state: "failure",
  status: 7,
  type: "NoSuchElement",
  value: null
}

This, given that my index.html only has a <h1 id="title">Hello world</h1> inside the body.
I also tried a few variations, such as getText('#title'), but the result is always the same.

@stepbeta
Copy link

The problem persists using [email protected]

@stepbeta
Copy link

I also tried using [email protected] and [email protected], which are the versions used by the electron-api-demos app.

With these versions, app.client.waitUntilWindowLoaded() does not give an error! This clearly show it's a regression of some sort.

Even though this step helps it going, I still receive the "an element could not be located..." error object.

@stepbeta
Copy link

My last comment is true on windows, but on Ubuntu the issue persists even with those versions of electron and spectron.

@juddey
Copy link

juddey commented Jul 31, 2017

Having the same issue with 3.7.2 on Elementary OS Loki (Ubuntu 16.04 base).

@TooBug
Copy link

TooBug commented Aug 1, 2017

Same issue on MacOS with spectron 3.7.2 and electron 1.6.11.

@TooBug
Copy link

TooBug commented Aug 1, 2017

Oh, I found the problem. It's because I opened the devtool in the main script. After disabling it, it works well.

@juddey
Copy link

juddey commented Aug 1, 2017

@TooBug Confirmed that fixed my issue (I was loading devtools in my prod build also.) Thanks!

@Smurf81
Copy link

Smurf81 commented Aug 21, 2017

@TooBug Thank you it save my day

@tansaku
Copy link

tansaku commented Aug 24, 2017

I had this issue too - perhaps we could add something to the README?

@cmdcolin
Copy link

cmdcolin commented Apr 2, 2018

This error can also occur if you set requireName to something and your app doesn't correspond properly.

E.g. I had set requireName: 'electronRequire' but my app forgot to change window.electronRequire = require;

            if(window.process&&process.versions&&process.versions.electron) {
                window.electronRequire = require;
                delete window.require;
            }

@karthik1407s
Copy link

Hi,
@TooBug Is disabling the devtools in main script done from development end or is there a way to do it through spectron(test side).?

thanks in advance
Karthik

@codebytere
Copy link
Member

Closing as this seems to have been resolved.

@albertotorresfoltyn
Copy link

Is not resolved, I still have the problem

@Ciriak
Copy link

Ciriak commented Feb 7, 2019

Encountering a similar issue when nodeIntegration is set to false

Not sure if this is an expected behaviour

this.browserWindow = new BrowserWindow({
      webPreferences: {
        nodeIntegration: false,
      }
    });

Failing test :

1) Opening editor
       opens a window:
     TypeError: waitUntilWindowLoaded Cannot read property 'isLoading' of undefined
      at waitUntil(<Function>, ) - C:\Users\cdelaunay\Desktop\Carnelian\node_modules\spectron\lib\application.js:229:17

  2) Opening editor
       "after each" hook for "opens a window":
     TypeError: Cannot read property 'exit' of undefined
      at Object.stopApp (test\hooks.js:26:29)
      at Context.afterEach (test\open_editor.js:11:17)

Edit :

It will become very problematic when nodeIntegration will be set to false by default in electron 5.0.0
image

artemv added a commit to artemv/angular-electron-spectron that referenced this issue Mar 1, 2019
according to electron-userland/spectron#174 (comment) this might help re error like in https://travis-ci.org/artemv/angular-electron-spectron/builds/500315009

..but this also could be node version dependent as I don't have it locally on MacOS & Node 9
@josiahruddell
Copy link

Using electron@5 you must set

webPreferences: {
  nodeIntegration: true,
},

This fixed my issue.

@scual
Copy link

scual commented Oct 10, 2019

The issue is still there in Electron 5.0.0 with Spectron 7.0.0: trying to access any of the app properties electron, webContents, browserWindow, with DevTools open will result in undefined.

@roman01la
Copy link

The issue is still present :(

@oldmtn
Copy link

oldmtn commented Jan 20, 2020

Report this issue if the libraries version is:

"electron": "^7.1.9",
"spectron": "^9.0.0"
"mocha": "^7.0.0",

It's ok if the libraries version is:

"electron": "1.8.2",
"mocha": "5.0.0",
"spectron": "3.8.0"

It's ok if the libraries version is:

    "electron": "^4.0.0",
    "spectron": "^6.0.0",
    "mocha": "5.0.0"

But if electron version is "5.0.0", then it will trigger an error like "TypeError: waitUntilWindowLoaded Cannot read property 'isLoading' of undefined"

OzymandiasTheGreat pushed a commit to OzymandiasTheGreat/emoji-keyboard that referenced this issue Feb 15, 2020
according to electron-userland/spectron#174 (comment) this might help re error like in https://travis-ci.org/artemv/angular-electron-spectron/builds/500315009

..but this also could be node version dependent as I don't have it locally on MacOS & Node 9
@sameoldmadness
Copy link

sameoldmadness commented Jul 26, 2020

It looks the issue is that webdriverio cannot see the main window if it was initialized ~50 ms after the app ready event.

Here's the minimal reproducible example.

// test.js
const electron = require('electron')
const { Application } = require('spectron')

const app = new Application({
  args: ['<cwd>/app.js'],
  path: electron,
})

Promise.resolve()
  .then(() => app.startChromeDriver())
  .then(() => app.createClient())
  .then(() => {
    return app.client
      .execute(function (requireName) {
        return typeof window[requireName] === 'function'
      }, 'require')
      .then(console.log)
  })

// app.js
const { app, BrowserWindow } = require('electron')

app.on('ready', () => {
  const w = new BrowserWindow()

  setTimeout(() => {
    w.loadURL('https://ya.ru')
  }, 5000)
})

As a workaround, one can load the blank page immediately. This fixes the aforementioned issue for me.

const { app, BrowserWindow } = require('electron')

app.on('ready', () => {
  const w = new BrowserWindow()

  w.loadURL('about:blank')

  setTimeout(() => {
    w.loadURL('https://ya.ru')
  }, 5000)
})

@VictorFouquet
Copy link

VictorFouquet commented Sep 30, 2020

Having the same issue here with

main.js :

`const { app, BrowserWindow } = require('electron')

function createWindow () {

const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})

win.loadFile('index.html')

//win.webContents.openDevTools()
}
app.whenReady().then(createWindow)

app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})

app.on('activate', () => {
if (win === null) {
createWindow()
}

})`

DevDependecies in package.json :

"devDependencies": { "electron": "^10.1.3", "mocha": "^8.1.3", "spectron": "^12.0.0" }

test script :

`const { Application } = require('spectron')
const assert = require('assert')
const electronPath = require('electron')
const path = require('path')

const myApp = new Application({
path: electronPath,
args: [path.join(__dirname, '..', 'main.js')]
})

const verifyWindowIsVisibleWithTitle = async (app) => {
await app.start()
try {
const isVisible = await app.browserWindow.isVisible()
assert.strictEqual(isVisible, true)
const title = await app.client.getTitle()
assert.strictEqual(title, 'My App')
} catch (error) {
console.error('Test failed', error.message)
}
await app.stop()
}
verifyWindowIsVisibleWithTitle(myApp)`

Error is the same wether win.webContents.openDevTools() is commented or not :

Test failed Cannot read property 'isVisible' of undefined
(node:15762) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'remote' of undefined
at /home/victorfouquet/Bureau/test-test/node_modules/spectron/lib/application.js:91:28
at new Promise ()
at Application.stop (/home/victorfouquet/Bureau/test-test/node_modules/spectron/lib/application.js:81:10)
at verifyWindowIsVisibleWithTitle (/home/victorfouquet/Bureau/test-test/test/spec.js:77:13)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:15762) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:15762) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

@Ali-Albaker
Copy link

I still have this issue

@rdandnayak
Copy link

I still am facing this issue
image

image

@AkatQuas
Copy link

image

Same issue with the following version

{
  "devDependencies": {
    "electron": "13.1.7",
    "electron-rebuild": "~2.3.5",
    "spectron": "~15.0.0"
  }
}

My simple test file

const assert = require('assert');
const path = require('path');
const electronPath = require('electron');
const { Application } = require('spectron');

const app = new Application({
  path: electronPath,
  env: {
    NODE_ENV: 'test',
  },
  args: [path.join(__dirname, '..')],
  webdriverOptions: {
    deprecationWarnings: false,
  },
});

app
  .start()
  .then(() => {
    return app.client.waitUntilWindowLoaded(5000);
  })
  .then(async () => {
    const visible = app.browserWindow.isVisible();
    assert.strictEqual(visible, true);
  })
  .catch((error) => {
    console.error('Test failed: ', error.message);
    console.error(error);
  });

Hercules2013 added a commit to Hercules2013/angular-electron that referenced this issue Oct 24, 2023
according to electron-userland/spectron#174 (comment) this might help re error like in https://travis-ci.org/artemv/angular-electron-spectron/builds/500315009

..but this also could be node version dependent as I don't have it locally on MacOS & Node 9
Boss930129 added a commit to Boss930129/angular_electron that referenced this issue Jun 6, 2024
according to electron-userland/spectron#174 (comment) this might help re error like in https://travis-ci.org/artemv/angular-electron-spectron/builds/500315009

..but this also could be node version dependent as I don't have it locally on MacOS & Node 9
francomattar added a commit to francomattar/Electron-Angular that referenced this issue Dec 12, 2024
according to electron-userland/spectron#174 (comment) this might help re error like in https://travis-ci.org/artemv/angular-electron-spectron/builds/500315009

..but this also could be node version dependent as I don't have it locally on MacOS & Node 9
artemsuvorov3 added a commit to artemsuvorov3/Electron-angular-artm that referenced this issue Jan 8, 2025
according to electron-userland/spectron#174 (comment) this might help re error like in https://travis-ci.org/artemv/angular-electron-spectron/builds/500315009

..but this also could be node version dependent as I don't have it locally on MacOS & Node 9
Soufiane88216 added a commit to Soufiane88216/Angular-electron that referenced this issue Jan 30, 2025
according to electron-userland/spectron#174 (comment) this might help re error like in https://travis-ci.org/artemv/angular-electron-spectron/builds/500315009

..but this also could be node version dependent as I don't have it locally on MacOS & Node 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.