Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a useragent in javascript?

I'm looking for a way to programmatically change navigator.userAgent on the fly. In my failed attempt to get an automated javascript unit tester, I gave up and attempted to begin using fireunit. Immediately, I've slammed into one of the walls of using an actual browser for javascript testing.

Specifically, I need to change navigator.userAgent to simulate a few hundred userAgent strings to ensure proper detection and coverage on a given function. navigator.userAgent is readonly, so I seem stuck! How can I mock navigator.userAgent? User Agent Switcher (plugin) can switch FF's useragent, but can I do it within javascript?

like image 338
Stefan Kendall Avatar asked Aug 20 '09 15:08

Stefan Kendall


People also ask

What is mocking in Javascript?

Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new , and allowing test-time configuration of return values.

What is navigator userAgent in Javascript?

The userAgent property returns the user-agent header sent by the browser to the server. The userAgent property is read-only. The value returned, contains information about the browser name, version and platform.


1 Answers

Try:

navigator.__defineGetter__('userAgent', function(){     return 'foo' // customized user agent });  navigator.userAgent; // 'foo' 

Tried it in FF2 and FF3.

like image 135
Crescent Fresh Avatar answered Oct 01 '22 11:10

Crescent Fresh