Overview

While testing you website, there might be a case where your website sends an HTTP request to a particular URL, but you do not want to send a request to that URL during the test run, and instead you just want to mock the response from that URL. Doing so is now possible with Nightwatch.

With Chrome DevTools Protocol support now available in Selenium 4, Nightwatch now supports intercepting the HTTP request and mocking the response from a particular URL.

This command only works with Chromium based browsers such as Google Chrome and Microsoft Egde.

Mock network response

This command allows you to mock the HTTP response from a particular URL. After running this command, whenever the URL of an HTTP request strictly matches with the URL passed into the command, the request is intercepted and the provided mock is sent back to the browser as the response.

All you need to do is call the browser.mockNetworkResponse() command with the required parameters before navigating to your website.

mockNetworkResponse() accepts a url (string type) as the first argument and a response object as the second argument. The specification of the response object are as follows:

key type default description
status number 200 HTTP status of the mocked response.
headers object {} HTTP headers in the mocked response.
E.g.: headers = {'Connection': 'Keep-Alive', 'Content-Type': 'UTF-8'}
body
optional
string '' Body of the mocked response.

Example

tests/mock-network-response.js
describe('mock network response', function() {
  it('intercepts the request made to Google search and mocks its response', function() {
    browser
      .mockNetworkResponse('https://www.google.com/', {
        status: 200,
        headers: {
          'Content-Type': 'UTF-8'
        },
        body: 'Hello there!'
      })
      .navigateTo('https://www.google.com/')
      .pause(2000);
  });
});