如何在Nightwatch JS中运行``窗口''JS命令 [英] How to run 'window' js command in nightwatch js

查看:82
本文介绍了如何在Nightwatch JS中运行``窗口''JS命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请我进行一些测试,具体取决于我的设备.在开始测试之前,我必须确定我的设备是移动设备还是台式设备.

Please i have some tests that varies depending on my device. I have to determine whether my device is mobile or desktop before beginning of a test.

我想在功能开始之前使用夜视仪,并在globals.js中添加了以下内容

I wanted to exploit the nightwatch before function and i added below in my globals.js

var self = module.exports = {
    environment: undefined,
    beforeEach: function (done) {
        self.environment = browser.window.navigator.userAgent;
        console.log("Run against: " + self.environment);
        done();
    },

};

我是我的测试

module.exports = {
    tags: ['assetindex'],
    'visit': function(browser) {
        (/Mobile/.test(browser.globals.environment)) ?
            browser
                .page.assetindex().mobileVisit()
                .end()
        :
            browser
                .page.assetindex().mobileVisit()
                .end()
    }
};

但是,我的代码在

self.environment = browser.window.navigator.userAgent;

未定义Widnow.考虑到我没有针对浏览器对象运行,该错误才有意义.请问我如何做到这一点?我怎样才能将js窗口靠在我的守夜浏览器中?任何帮助或替代方案都将受到高度赞赏

saying widnow not defined. The error makes sense considering i am not running against a browser object . Please how do i achieve that? How can i the js window against my browser in nightwatch ? Any help or alternative is highly appreciated

更新

阅读下面的答案后,我将global.js更新为

After reading the answer below, i update my global.js to

var self = module.exports = {
    environment: undefined,

    beforeEach: function (browser, done) {
        browser.execute(function(data) {
            return window.navigator.userAgent;
        }, [], function(result) {
            console.log('it comes here ', result);
            self.environment = result.value;
        });

        console.log("Run against: " + self.environment);
        done();
    },

};

令我惊讶的是,self.environment始终是不确定的.它似乎没有运行.exec函数.

TO my surprise, self.environment is always undefined. It does not seem to be running the .exec function.

推荐答案

您可能可以使用execute命令:

browser.execute(function(data) {
    return window.navigator.userAgent;
}, [], function(result) {
    self.environment = result.value;
});

有关更多信息: http://nightwatchjs.org/api/execute.html

在您的情况下,使用beforeEach时,您需要在回调函数内移动done(),如下所示:

In your case, when using beforeEach you need to move the done() inside the callback function, like so:

beforeEach: function (browser, done) {
    browser.execute(function(data) {
        return window.navigator.userAgent;
    }, [], function(result) {
        console.log('it comes here ', result);
        self.environment = result.value;
        console.log("Run against: " + self.environment);
        done();
    });
},

这篇关于如何在Nightwatch JS中运行``窗口''JS命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆