Pranesh Ravi Pranesh Ravi - 1 year ago 253
Javascript Question

Relative URL as hostname in Nock

I need to mock client side HTTP requests. I'm using

in the client side and I'm using
for testing and mocking. All my client requests are based on relative path. Due to this I'm unable to provide host name for the
. Is there a work around.

Client side:

fetch('/foo') //hostname: http://localhost:8080
.then(res => res.json())
.then(data => console.log(data))
.catch(e => console.log(e))

Test suite

.reply(200, {data: "hello"})

This is failing as I'm not giving the proper hostname for the
. Am I doing something wrong?

Answer Source

Found a workaround for this. Have a _ajax-setup.js in your test folder

import $ from 'jquery'

$(document).ajaxSend((event, jqxhr, settings) => {
  settings.url = '' + settings.url;

The thing to note is that this file has to run First and Only Once. Having it as a file runs only once and _ before it makes it alphabetically first.

Later you can test your code with

.reply(200, {data: "hello"})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download