简体   繁体   中英

Nightwatch.js: window is undefined

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?

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

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.

窗口未定义 ..这是当您使用窗口函数而不使用 process.browser 函数时首先出现错误 [1]: https : //i.stack.imgur.com/w2BdT.png解决方案:[2]: https://i .stack.imgur.com/kggMb.png

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM