My last question for today is not really a question, I would like to have your opinion about this JasmineJS test code I created to test if user entered alphanumeric or not.
I have an HTML input box called username:
Username: <input type="text" name="username" id="username" class="input" value="testinput" />
I created a Javascript function to filter user input if the input is alphanumeric or not.
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;
}
Inside my JasmineJS folder I created a service file to test the filter user input feature. My service goes like this:
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;
}
};
Then my jasmine script goes like this:
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);
});
});
Everythings works just fine, but I am concerned about the validity of the test. Bottom question is, is this the correct way to test the javascript function with JasmineJS? Thanks
A good test, as well as good code is modular. You are just testing if your code returns false. To check if your code is correctly testing if a string is alphanumeric you would want to test it against strings that are alphanumeric as well as strings that aren't alphanumeric. I would pass the string into the function you are testing.
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#$$@@')).toEqual(false);
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.