I want to write some test cases for touch events. In my code I have the following logic to decide whether it is on touch devices.

if(document.documentElement.ontouchstart !== undefined)
 //content that I want to write test cases about

Now I want to fake document.documentElement.ontouchstart not to be undefined, so the inside logic will be executed.

I tried using Sinon.js‘s stub to assign an empty function to document.documentElement.ontouchstart. But it will throw an error indication “TypeError: Attempted to wrap undefined property ontouchstartas function” since document.documentElement has no such property in browser.

I really don’t want to write something like: document.documentElement.ontouchstart = function() {..} in my test since it will effect other test cases. Of course I can store the original value of it and restore the value when the test case is over. But I wanna to ask, is there any more elegant way to achieve this?

How to make it to go into if statement?