2015-11-23 39 views
0

我今天的最後一個問題並不是真正的問題,我想對您創建的JasmineJS測試代碼有意見,以測試用戶是否輸入了字母數字。測試輸入是字母數字還是不使用JasmineJS

我有稱爲用戶名的HTML輸入框:

Username: <input type="text" name="username" id="username" class="input" value="testinput" /> 

我創建Javascript函數來過濾用戶輸入,如果輸入是字母數字或沒有。

function acceptOnlyAlphanumeric() { 
    var usernameInput = document.register.username.value; 

    if(!/^[a-zA-Z0-9]+$/.test(usernameInput)) { 
    console.log("Please enter only numbers and letters. No special character!") 
    return true; 
    } 
    return false; 
} 

在我的JasmineJS文件夾中,我創建了一個服務文件來測試過濾器用戶輸入功能。我的服務是這樣的:

Services = { 
    userFilter : function() { 
    var usernameInput = 'ThisIsAnAlphanumeric112233'; 

    if(!/^[a-zA-Z0-9]+$/.test(usernameInput)) { 
     console.log("Please enter only numbers and letters. No special character!") 
     return true; 
    } 
     return false; 
    } 
}; 

然後,我的茉莉花腳本是這樣的:

describe("Test if user enters an acceptable user input which is alphanumeric", function() { 
    it("Should test if user enters alphanumeric or not", function() { 
     expect(Services.userFilter()).toEqual(false); 
    }); 
    }); 

萬物工作得很好,但我關心的測試的有效性。底部的問題是,這是用JasmineJS測試JavaScript函數的正確方法嗎?謝謝

回答

1

一個好的測試,以及良好的代碼是模塊化的。你只是測試你的代碼是否返回false。要檢查您的代碼是否正確測試字符串是否是字母數字,您需要對字母數字字符串以及非字母數字字符串進行測試。我會將字符串傳遞給您正在測試的函數。

Services = { 
    userFilter : function (userInput) { 
    //var usernameInput = 'ThisIsAnAlphanumeric112233'; 
    if(!/^[a-zA-Z0-9]+$/.test(userInput)) { 
    console.log("Please enter only numbers and letters. No special character!") 
    return true; 
    } 
    return false; 
    } 
}; 




    describe("Test if user enters an acceptable user input which is alphanumeric", function() { 
    it("Should test if user enters alphanumeric or not", function() { 
     expect(Services.userFilter('ThisIsAnAlphanumeric112233')).toEqual(true); 
    }); 
    }); 
describe("Test if user enters an acceptable user input which is alphanumeric", function() { 
    it("Should test if user enters alphanumeric or not", function() { 
     expect(Services.userFilter('ThisIsAnAlphanumeric#[email protected]@')).toEqual(false); 
    }); 
    }); 
+0

OMG非常感謝你。 。你剛剛打開了我的第三隻眼睛叫JasmineJs。 。 :)我現在完成了JasmineJS的基本知識。非常感謝您的示範。 。 :)解決 – Neil

+0

所以爲了澄清,可以將參數「userInput」更改爲任何參數名稱,如「input」或「inputValue」。 。 ? :) – Neil

+0

我測試了它,並改變參數userInput後仍然工作。 – Neil

相關問題