vendredi 6 février 2015

Unit Testing Javascript with Jasmine

I am very new to Jasmine and Unit testing in general.This is my first ever unit test.Anyways,I am testing a function which does not receive parameters.I have written some code,but I am facing an error with the validation code in the Javascript to be tested.


The Javascript functions to be tested: formatPhoneNumber and formatSSN



var Provider = function () {
var self = this;
self.SSN = ko.observable("");
self.contactNumber = ko.observable("");
self.formatPhoneNumber = function () {
if (self.contactNumber().length == 10) {
self.contactNumber(self.contactNumber().replace(/(\d{3})(\d{3})(\d{4})/, "($1)$2-$3"));
$("#contactNumber").rules("remove", "max");
$("#contactNumber").rules("add", { maxlength: 13 });
}
};
self.formatSSN = function () {
if (self.SSN().length == 9) {
self.SSN(self.SSN().replace(/(\d{3})(\d{2})(\d{4})/, "$1-$2-$3"));
$("#SSN").rules("remove", "max");
$("#SSN").rules("add", { maxlength: 11 });
}
};
}; //Provider Constructor ends here
$(document).ready(function () {
ko.applyBindings(new Provider());
jQuery.validator.addMethod("acceptEmail", function (value, element) {
return this.optional(element) || /^([\w\d\-\.]+)@{1}(([\w\d\-]{1,67})|([\w\d\-]+\.[\w\d\-]{1,67}))\.(([a-zA-Z\d]{2,4})(\.[a-zA-Z\d]{2})?)$/.test(value);
});
$("#providerDetailsForm").validate({
onfocusout: function (element, event) {
this.element(element);
},
onkeyup: function (element, event) {
if (event.which === 9 && this.elementValue(element) === '') {
return;
} else if (element.name in this.submitted) {
this.element(element);
}
},
rules:
{

SSN: { required: true, minlength: 9, maxlength: 9 },
contactNumber: { required: true, minlength: 10, maxlength: 10 },
},
messages: {
SSN: {
required: "Please enter the SSN",
minlength: "Invalid SSN(9 Digits atleast)",
maxlength: "Invalid SSN(9 Digits only)"
},
contactNumber: {
required: "Please enter the Contact Number",
minlength: "Enter a 10 digit contact number",
maxlength: "Enter a 10 digit contact number"
},
}
});
});


The Jasmine tests is



/// <reference path="../../App_Scripts/CreateProvider.js" />
/// <reference path="../jquery-2.1.3.min.js" />
/// <reference path="../jquery.validate.min.js" />
/// <reference path="../lib/jasmine.js" />

describe("ProviderSpec", function () {
var provider;
beforeEach(function () {
provider = new Provider();
});
it("should format a phone number", function (done) {
provider.contactNumber("1234567890");
provider.formatPhoneNumber();
expect(provider.contactNumber()).toBe('(123)456-7890');
done();
});
});


The jasmine scripts and the scripts to be tested are in the same project.Even though I have included the validator plugin,I am not able to run this test.I keep getting an error related to the plugin.Could someone please guide me in the right direction.


Aucun commentaire:

Enregistrer un commentaire