首页 > 解决方案 > 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.');
      }
    });
  }
};

你知道如何强制自动测试忽略主页吗?

或者你知道如何在 nightwatch.js 中使用window.location.hostwindow.location.protocol?我问它,因为我知道如何使用清晰的 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);
    }
}

标签: javascriptjquerynightwatch.jsautotestnightwatch

解决方案


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

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.');
                                }
                            });
                        }
                    });

                }
            }
        );
    }
};


推荐阅读