Nightwatch.js: window is undefined
Asked Answered
A

3

7

I'm trying to use Nightwatch to test a React application. I'm using React-Router with it.

When running my test with Nightwatch window is undefined.

React uses the following snippet to test if the DOM is available:

var canUseDOM = !!(
  typeof window !== 'undefined' &&
  window.document &&
  window.document.createElement
);

From React.js source: ExecutionEnvironment.js#L16

React-Router expects canUseDOM to be true, otherwise it throws an error.

So my test fails because window is undefined when running Nightwatch.

Shouldn't window be present with selenium webdriver? How can I make window available?

Ascarid answered 18/4, 2015 at 9:17 Comment(4)
Can you put some more details? Where are you executing that check?Mayflower
You mean canUseDOM? This is part of React. React-Router throws an error if canUseDOM is false, which it is because window is undefined when running Nightwatch.Ascarid
So React is throwing the Error as the WebDriver browser load the page?Mayflower
React-Router is throwing the error when trying to do Router.runAscarid
R
11

From Nighwatch.js (and selenium-webdriver, more specifically) you cannot directly access to the DOM of the client. You must use the execute() function to inject your script :

 this.demoTest = function (browser) {
   browser.execute(function(data) {

     var canUseDOM = !!(
       typeof window !== 'undefined' &&
       window.document &&
       window.document.createElement
     );
     alert('canUseDOM ?' + canUseDOM); 

     return true;
   }, [], null);
 };

More info in the API : http://nightwatchjs.org/api#execute

Rufford answered 21/4, 2015 at 6:14 Comment(1)
This code works.. But removing that unwanted alert cause execute to hang?Indigestion
A
0

It turns out I was loading application code in my test without noticing, my nightwatch configuration wasn't quite right. So this is where the error was being raised, because Nightwatch was trying to access window in the test code.

Ascarid answered 21/4, 2015 at 11:4 Comment(0)
O
0

window is undefined ..this comes when you use window function without using process.browser function first Error [1]: https://i.sstatic.net/w2BdT.png solution: [2]: https://i.sstatic.net/kggMb.png

Once answered 1/12, 2021 at 10:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.