13

how do I check the HTTP status code using nightwatch.js? I tried

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

but of course that does not work.

Brown A
  • 929
  • 4
  • 14
  • 21
  • Possible duplicate of [How to get HTTP Response Code using Selenium WebDriver with Java?](https://stackoverflow.com/questions/6509628/how-to-get-http-response-code-using-selenium-webdriver-with-java) – SiKing Nov 03 '17 at 21:16
  • not duplicate, this question related to nightwatch JS – Raj Kumar Samala Jul 05 '18 at 11:49

3 Answers3

7

Actually there is no way yet to get the response status of the page using Selenium (https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/141)

But what you can easily do is require "request" library, make your request to the webpage you want to open in your Selenium tests and validate that response status code equals 200:

const request = require('request');

request('http://stackoverflow.com', (error, response, body) => {
    browser.assert.equal(response.statusCode, 200);
});
Ilarion Halushka
  • 2,083
  • 18
  • 13
4

Try this

    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();
         }
       };
Madhumitha
  • 41
  • 6
3

Supplementing to Hilarion Galushka's answer: you can use the perform() command from nightwatch to intergrate request and assert into your nightwatch tests. http://nightwatchjs.org/api/perform.html

For example:

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()
            });
        })
    }
}
mibemerami
  • 61
  • 1
  • 2