【问题标题】:check http status code using nightwatch使用 nightwatch 检查 http 状态码
【发布时间】:2023-03-02 22:18:01
【问题描述】:

如何使用 nightwatch.js 检查 HTTP 状态代码?我试过了

  browser.url(function (response) {
     browser.assert.equal(response.statusCode, 200);
  });

但这当然行不通。

【问题讨论】:

标签: selenium nightwatch.js


【解决方案1】:

试试这个

    var http = require("http");
    module.exports = {
      "Check Response Code" : function (client) {
          var request = http.request({
            host: "www.google.com",
            port: 80,
            path: "/images/srpr/logo11w.png",
            method: "HEAD"
          }, function (response) {
            client
            .assert.equal(response.statusCode, 200, 'Check status');
            client.end();
          }).on("error", function (err) {
            console.log(err);
            client.end();
          }).end();
         }
       };

【讨论】:

    【解决方案2】:

    其实目前还没有办法使用 Selenium 获取页面的响应状态(https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/141

    但是您可以轻松地做的是需要“请求”库,向您要在 Selenium 测试中打开的网页发出请求并验证响应状态代码等于 200:

    const request = require('request');
    
    request('http://stackoverflow.com', (error, response, body) => {
        browser.assert.equal(response.statusCode, 200);
    });
    

    【讨论】:

      【解决方案3】:

      补充 Hilarion Galushka 的回答:您可以使用 nightwatch 中的 perform() 命令将请求和断言集成到您的 nightwatch 测试中。 http://nightwatchjs.org/api/perform.html

      例如:

      module.exports = {
          'test response code': function (browser) {
              browser.perform(done => {
                  request('http://stackoverflow.com', function (error, response, body) {
                      browser.assert.equal(response.statusCode, 200);
                      done()
                  });
              })
          }
      }
      

      【讨论】:

      • 这是 IMO 的最佳答案。
      猜你喜欢
      • 1970-01-01
      • 2014-10-13
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 2012-12-22
      • 1970-01-01
      • 2010-12-26
      • 1970-01-01
      相关资源
      最近更新 更多