Search code examples
seleniumnightwatch.jsnock

Nock does not work with Nightwatch + Selenium


I am using nock to mock my http requests.

My app is written using Redux + React.

import nock from "nock"

nock("http://localhost:8080")
  .log(console.log)
  .get("/fake/users/sign_in.json")
  .reply(500, 'Error')

const doLogin = (browser) => {
  return browser
          .url("http://localhost:8080")
          .waitForElementVisible('form', 1000)
          .setValue('input[name=email]', '[email protected]')
          .setValue('input[name=password]', 'somepass')
          .click('button[type=submit]')
          .pause(500)
}

export default {
  "Do login and receive success message": (browser) => {
    doLogin(browser)
      .assert.urlContains('panel')
      .end()
  }
}

When the request returns error 500 can not pass the test, but currently it passes. So I think that nock is not mocking the requests.


Solution

  • You have to use

    ...
    .execute(`var importScript = (function (oHead) {
    
      function loadError (oError) {
        throw new URIError("The script " + oError.target.src + " is not accessible.");
      }
    
      return function (sSrc, fOnload) {
        var oScript = document.createElement("script");
        oScript.type = "text\/javascript";
        oScript.onerror = loadError;
        if (fOnload) { oScript.onload = fOnload; }
        oHead.appendChild(oScript);
        oScript.src = sSrc;
      }
    
        })(document.head || document.getElementsByTagName("head")[0]);
         importScript('http://somewhere.com/nock.js')`)