Nightwatch.js 如何忽略主页?或者如何使用window.location.host?

问题描述

我是 nightwatch.js 的大菜鸟,但我必须决定这个任务。请帮帮我...

我有一个简单的自动测试,测试的本质是在网站的每个页面上寻找指向主页的链接,如果链接少于 2 个,则测试不会通过并给出错误

module.exports = {
  disabled: false,name: 'Homepage links',subtitle: ['There are less than 2 links to the main page.'],fn: function(browser) {
    browser.elements('css selector','a[href="/"]',function(result) {
      let allLinksToMain = result.value.length;

      if (allLinksToMain < 2) {
        browser.verify.ok(false,'There are less than 2 links to the main page.');
      }
    });
  }
};

您是否知道如何强制自动测试忽略主页

或者您是否知道如何将 window.location.hostwindow.location.protocol 与 nightwatch.js 结合使用?我问它,因为我有一些想法如何用清晰的 JavaScript 决定我的任务,但它不适用于 nightwatch.js:

let mainPageUrl = window.location.protocol + "//" + window.location.host + "/";
let currentUrl = window.location.href;

let findLinks = document.querySelectorAll('a[href="/"]');

if (currentUrl === mainPageUrl) {
    console.log('This is the main page,do nothing!');
} else {
    console.log('Current URL: ' + currentUrl);
    if (findLinks.length >= 2) {
        console.log("The test passed without errors,links to the main page - " + findLinks.length);
    } else {
        console.log("The test didn't pass,links to the main page - " + findLinks.length);
    }
}

解决方法

好的,我已经做到了!我希望它会帮助某人:)

module.exports = {
    disabled: false,name: 'Homepage links',subtitle: [
        'There are less than 2 links to the main page.','There is less than 1 link in logo.',],fn: function(browser) {
        browser.execute(
            function() {
                let mainPageUrl = window.location.protocol + "//" + window.location.host + "/";
                let currentUrl = window.location.href;
                return result = {
                    main: mainPageUrl,current: currentUrl,}
            },[],function(result) {
                if (result.value.current !== result.value.main) {

                    browser.elements('css selector','a[href="/"]',function(result) {
                        if (result.value.length < 2) {
                            browser.verify.ok(false,'There are less than 2 links to the main page.');
                        } else {
                            browser.elements('css selector','a[href="/"] > img,a[href="/"] > svg',function(result) {
                                if (result.value.length < 1) {
                                    browser.verify.ok(false,'There is less than 1 link in logo.');
                                }
                            });
                        }
                    });

                }
            }
        );
    }
};