javascript - Nightwatch 获取 api 结果以填充变量然后运行使用该变量的测试的正确方法

标签 javascript node.js asynchronous nightwatch.js

我是 Node 和异步处理方式的新手。

我想使用 nightwatch.js 创建并运行一个测试套件,我已经阅读了所有文档,但我对如何做我想做的事情感到困惑(已经研究了 3 天)。

我是不是想错了?

module.exports = {
    before: function(browser) {
        /*
        Here I just want to make a web call to an api and get a result and then
        store that result in a variable which we will use later in test1 and other test cases
        */
        browser.globals.myVariable = resultofsomeapicalll;
        //wait here until proceeding
    },
    after: function(browser) {
        browser.end();
    },
    beforeEach: function(browser) {
    },
    afterEach: function() {
    },
    'test1': function(browser) {
        browser.url(browser.launchUrl + browser.globals.myVariable, function(result) {
            browser.waitForElementPresent('body', 1000);
            browser.expect.element("#something").to.be.present;
            browser.saveScreenshot('./screenshots/' + browser.currentTest.module + '/' + browser.currentTest.name + '.png');
        });
    },
};

最佳答案

要在 Nightwatch.JS 的 before[Each] 或 after[Each] Hook 中执行异步任务,您需要将回调参数传递给该函数,该函数将在作业完成后触发。

在下面的示例中,它将是一个使用 Axios 的 API 调用图书馆;

module.exports = {
    before: function(browser, done) {
        axios.get('https://example.com/api?ID=12345')
          .then(function (response) {
            browser.globals.myVariable = response;
            done();
          })
          .catch(function (error) {
            done(error);
          });
    },
    after: function(browser) {
        browser.end();
    },
    beforeEach: function(browser) {
    },
    afterEach: function() {
    },
    'test1': function(browser) {
        console.log()
    },
};

Controlling the done invocation timeout

By default the done invocation timeout is set to 10 seconds (2 seconds for unit tests). In some cases this might not be sufficient and to avoid a timeout error, you can increase this timeout by defining an asyncHookTimeout property (in milliseconds) in your external globals file (see below for details on external globals).

http://nightwatchjs.org/guide/#asynchronous-before-each-and-after-each-

最好的问候,

关于javascript - Nightwatch 获取 api 结果以填充变量然后运行使用该变量的测试的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47806896/

相关文章:

Javascript:对象 ['name' ] 问题

javascript - .NET Core API 与来自 JavaScript 的 CORS

javascript - 如何扩展正则表达式对象

node.js - winston 中的纯文件日志记录

c# - Task.Run 与 Invoke() 区别

javascript - Jquery:模糊功能不适用于 Div 标签

javascript - 使用 require.js 加载 browserify boundle.js

node.js - 通过 nodejs 访问谷歌分析

javascript - 我如何异步拦截点击

java - 为什么我的 @Async Future<T> 会阻塞?