0

I've wrote a javascript method that changes the value of a suggestbox on a click of an image.

function startDestinationF(a) {
var startDestination = document.getElementById('startDestination');
startDestination.selectedIndex = (a);}

Now i have to write a jasmine testcase to check if this method really works but i don't really get it.

i've tried:

describe("Change onclick the value of the drop down menu", function() {

var startDestination;

beforeEach(function() {
    startDestination = document.getElementById('startDestination'); 
  });

it("should change the value", function() {
    expect(startDestinationF(3)).toBe(startDestination.selectedIndex==3);
});});

but it says: "Cannot read property 'selectedIndex' of null". I'm a newbie on that field and i could really need some help...

thanks

DayTimeCoder
  • 4,294
  • 5
  • 38
  • 61
Alex Baur
  • 165
  • 1
  • 2
  • 11

4 Answers4

1

You must have and element with id startDestination in your DOM.

Two ways of achieving this:

  • Hardcode the element into the body element of SpecRunner.html
  • Create the element with JavaScript and append it to the DOM before running that test.
1

old question, but in case someone will find it

it("should work", myTestFunction.bind(this, 'param1','param4'));
it("should work", myTestFunction.bind(this, 'param2','param3'));

function myTestFunction(param1, expected){
   expect(param1).toBe(expected);
}

i use bind to make copies of my function with necessary params

Anatoli Klamer
  • 2,279
  • 2
  • 17
  • 22
0

As with Jasmine it is crucial you need to create the element with ID in DOM. There are many ways you can do this and the way i do is using jasmine-fixture

affix('#startDestination')  --> This will create this in DOM <div id="startDestination">

If you need to have specific type of input you can do that too.

skusunam
  • 411
  • 3
  • 12
0

This is one way you could do it and this is normally how I do this. I took the liberty of using jQuery for this :)

Here's a working plunkr: http://plnkr.co/edit/93dyzvxa82sFWWFZ6NTi?p=preview

describe('test suite', function(){
   // this here represents your global function
   // I've added this here for the purpose of this demo
   function setValue(a) {
       $('#name').val(a);
    }       

   beforeEach(function(){
      this.element = $('<input id="name" type="text" />');
      this.element.appendTo('body');
   });

   // clean up
   afterEach(function(){
      this.element.remove(); 
   });

   it('should change the value', function(){
      //when
      setValue('Alex Baur');

     // then
     expect(this.element.val()).to.Equal('Alex Baur');
   });
});
mengstrom
  • 233
  • 3
  • 13