Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
199
rated 0 times [  200] [ 1]  / answers: 1 / hits: 119500  / 14 Years ago, tue, january 25, 2011, 12:00:00

I have some unit tests for a function that makes use of the window.location.href -- not ideal I would far rather have passed this in but its not possible in the implementation. I'm just wondering if its possible to mock this value without actually causing my test runner page to actually go to the URL.



  window.location.href = http://www.website.com?varName=foo;    
expect(actions.paramToVar(test_Data)).toEqual(bar);


I'm using jasmine for my unit testing framework.


More From » mocking

 Answers
23

You need to simulate local context and create your own version of window and window.location objects



var localContext = {
window:{
location:{
href: http://www.website.com?varName=foo
}
}
}

// simulated context
with(localContext){
console.log(window.location.href);
// http://www.website.com?varName=foo
}

//actual context
console.log(window.location.href);
// http://www.actual.page.url/...


If you use with then all variables (including window!) will firstly be looked from the context object and if not present then from the actual context.


[#94064] Sunday, January 23, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leog

Total Points: 225
Total Questions: 113
Total Answers: 118

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
;