Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unit testing for an input field using jasmine

I have a form inside javascripts/fixtures/form.html. I am checking for whether my field is empty or contains less than eight character or has special characters.

  it("Username should not be empty", function(){
        spyOn($("#name"), "val").and.returnValue("Java");
        var result = $("#name").val();
        expect(result).toEqual("Java");
    });

    it("Username should be of the length greater than eight", function(){
        spyOn($("#name"), "val").and.returnValue("Java");
        var result = $("#name").val();
        expect(result).toEqual("Java");
    });

    it("Username should not contain special characters", function(){
        spyOn($("#name"), "val").and.returnValue("Java");
        var result = $("#name").val();
        expect(result).toEqual("Java");
    });

I am not sure whether this is the right way to do unit testing. Can anyone guide me on how to do unit testing for an input field on these three cases.

like image 968
theJava Avatar asked Jun 28 '26 17:06

theJava


1 Answers

You can not check the input data directly with this:

   var result = $("#name").val();
   expect(result).toEqual("Java");

To check your input field value, you can load/set the fixtures and can assign the value to your fixtures and can read the fixtures' input data then you can check with .toEqual("") or something else.

You can refer this code to check the input field value:

var value = 'some value';
var differentValue = 'different value';

beforeEach(function () {
  setFixtures($('<input id="sandbox" type="text" />').val(value));
});

it("should pass if value matches expectation", function () {
  expect($('#sandbox')).toHaveValue(value);
  expect($('#sandbox').get(0)).toHaveValue(value);
});

I hope this url will help you bit more to understand the fixtures: https://github.com/velesin/jasmine-jquery/#cross-domain-policy-problems-under-chrome

like image 136
user3428816 Avatar answered Jul 01 '26 20:07

user3428816