我想寫一些觸摸事件的測試用例。在我的代碼中,我有以下邏輯來決定它是否在觸控設備上。如何使用桌面瀏覽器測試觸摸事件?
if(document.documentElement.ontouchstart !== undefined)
{
//content that I want to write test cases about
}
現在我想假document.documentElement.ontouchstart
不被undefined
,所以內部的邏輯將被執行。
我試着用Sinon.js
的stub
給document.documentElement.ontouchstart
分配一個空函數。但它會拋出一個錯誤指示「TypeError:試圖將未定義屬性ontouchstart
作爲函數」,因爲document.documentElement
在瀏覽器中沒有此屬性。
我真的不想在我的測試中寫下類似document.documentElement.ontouchstart = function() {..}
的東西,因爲它會影響其他測試用例。當然,我可以存儲它的原始值,並在測試用例結束時恢復它的值。但是我想問一下,有沒有更好的方法來實現這個目標?
如何使它進入if
聲明?
你可以調用/觸發onmousedown事件ontouchstart –
@ABUdhay但我想檢查'if'裏面的邏輯。觸發'onmousedown'不會讓'if'語句變爲true。 – JasmineOT
這就是基本上在Dom中它不會在那裏..你有添加一個方法domelement對象像document.documentElement.ontouchstart = function(){//在這裏你必須調用onmousedown的回調函數或觸發mousedown事件處理程序方法} –