通过nighwatch

时间:2015-09-19 16:10:02

标签: javascript nightwatch.js

我是守夜人的新手。发现它在自动化测试中非常有用。但是,我遇到了一个问题&我找不到解决方案。请帮我解决这个问题。

请考虑以下代码:

module.exports = {
    'testcase1' : function(browser) {
        //GET SOME LINKS HERE DYNAMICALLY
    },

    'testcase2' : function(browser) {
        //FOR EACH OF THE LINKS OBTAINED IN 'testcase1', DO THE FOLLOWING:
        //OPEN THE LINK, CLICK ON A PARTICULAR ELEMENT(I KNOW THE ELEMENT HERE, SO THATS NOT AN ISSUE) & TAKE A SCREENSHOT    
    } 
};

所以我会动态地获得一些链接&我想运行' testcase2'在每个人身上,不会影响彼此的执行。我试过循环,但由于javascript是异步,所以没有帮助。

1 个答案:

答案 0 :(得分:0)

执行循环的一种方法是循环执行命令。 Nightwatch会跟踪命令的顺序并为您维护。这将使它可以从一个命令链接到下一个命令。

将两个测试中使用的获取链接代码放入命令中。还要将代码放在另一个命令中使用链接。

命令可以位于自己的文件夹中,也可以在Page对象中创建。假设你去创建一个命令文件夹,将文件夹路径添加到nightwatch.json的顶部,如"custom_commands_path" : "commands",

然后创建文件。它们看起来像这样:

// put this command in a file named 'getLinks'
exports.command = function() {
    var self = this;
    var globals = self.globals;

    //do stuff to get links
    //make links accessible by other commands
    globals.links = links;

    return self;
};

// put this command in file named 'useLinks'
exports.command = function() {
    var self = this;
    var links = self.globals.links;

    // note you don't have to use _.js here. 'for (var i; i < links.length...' works fine too.
    _.each(links, function (link) {
        //do something with the link
        self.url('theUrlWithTheLinks')
            .click(link)
            //use commands for each thing to do 
            //this way it is chainable and order is maintained
            .click(someElement)
            .takeTheNeededScreenshot();
    })
    return self;
};

//tests
module.exports = {
    'testcase1' : function(browser) {
        //GET SOME LINKS HERE DYNAMICALLY
        browser.getLinks()
    },

    'testcase2' : function(browser) {   
        browser.getLinks()
            .useLinks()
            //chain more commands
            .end();

    } 
};