Sinon.JS stub for window.location.search

I am trying to test a simple function that calls the window.location.search call. I am trying to figure out how to drown out this call so that I can return the URL of my choice.

function:

getParameterByName: (name) =>    
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]")
  regexS = "[\\?&]" + name + "=([^&#]*)"
  regex = new RegExp(regexS)    
  results = regex.exec(window.location.search) //Stub call to window.location.search
  if(results == null)
    return ""
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "))

Test case:

describe "Data tests", () ->
  it "Should parse parameter from url", () ->        
    data = new Data()

    console.log("search string: " + window.location.search) //prints "search string:"
    window.location.search = "myUrl"
    console.log("search string: " + window.location.search) //prints "search string:"
    console.log(data.getParameterByName('varName'))

    expect(true).toBe(true)

My initial attempt was to return the value directly like this:

sinon.stub(window.location.search).returns("myUrl")

This, of course, does not work. I do not think that I correctly identify the stub, but it shows my intentions.

Any ideas on how to solve this problem would be very helpful.

+5
source share
2 answers

, , . mylib.search . , , , window.location.search . :

getParameterByName: (name) =>
  console.log("name: #{name}")
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]")
  regexS = "[\\?&]" + name + "=([^&#]*)"
  regex = new RegExp(regexS)
  results = regex.exec(@getWindowLocationSearch())
  if(results == null)
    return ""
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "))

getWindowLocationSearch:() =>
  window.location.search

:

describe "Data tests", () ->
  it "Should parse parameter from localhost url", () ->
    goodUrl = "http://localhost:3333/?token=val1"

    Data::getWindowLocationSearch = () -> return goodUrl
    unit = new Data()
    result = unit.getParameterByName("token")

    expect(result).toBe("val1")

, Coffeescript, javascript :

it("Should parse parameter from localhost url", function() {
  var goodUrl, result, unit;
  goodUrl = "http://localhost:3333/?token=val1";
  Data.prototype.getWindowLocationSearch = function() {
    return goodUrl;
  };
  unit = new Data();
  result = unit.getParameterByName("token");
  expect(result).toBe("val1");
  return expect(true).toBe(true);
});

Javascript. , . .

+6

UPDATE: window.location, , , . : https://groups.google.com/forum/?fromgroups#!topic/sinonjs/MMYrwKIZNUU%5B1-25%5D

The easiest way to solve this problem is to write a wrapper function around window.locationand smooth out that:

mylib.search = function (url) {
  window.location.search = url;
};

And in your test:

sinon.stub(mylib, 'search').returns("myUrl")

ORIGINAL RESPONSE:

Try the following:

sinon.stub(window.location, 'search').returns("myUrl")
+2
source

All Articles