Manoj Masakorala
Manoj Masakorala

Reputation: 446

How to unit test conditional statements in jasmine

Can any one help me with testing conditional statement within a function in jasmine

vm.onDisciplineCodeChange = function() {
                if ('other' === vm.selectedDisciplineCode) {
                    vm.selectedDiscipline.code = null;
                    vm.selectedDiscipline.userDefined = true;
                } else if('' === vm.selectedDisciplineCode) {
                    vm.selectedDiscipline = {
                        code: null,
                        userDefined: false,
                        userDefinedDiscipline: null
                    }
                } else {
                    vm.selectedDiscipline = {
                        code: vm.selectedDisciplineCode,
                        userDefined: false,
                        userDefinedDiscipline: null
                    }
                }
                vm.onDisciplineUpdated({discipline: vm.selectedDiscipline});
            };

I'm quite new to unit testing and following is the output i'm getting in generated report.

enter image description here

Upvotes: 2

Views: 7369

Answers (1)

Jayant Patil
Jayant Patil

Reputation: 1587

You see it because of it is not covered in unit testing Use following code to cover it in unit testing

it('if discipline is other', function() {
  // spy on
  spyOn(vm, 'onDisciplineUpdated');

  vm.selectedDisciplineCode = 'other';
  vm.onDisciplineCodeChange();
  expect(vm.selectedDiscipline.code).toBe(null);
  expect(vm.selectedDiscipline.userDefined).toBe(true);
  expect(vm.onDisciplineUpdated).toBeCalledWith({
    discipline: vm.selectedDiscipline
  });
})

it('if discipline is null', function() {
  vm.selectedDisciplineCode = '';
  vm.onDisciplineCodeChange();
  var result = {
    code: null,
    userDefined: false,
    userDefinedDiscipline: null
  };
  expect(vm.selectedDiscipline).toBe(result);
})


it('if discipline is different', function() {
  vm.selectedDisciplineCode = 'nothing';
  vm.onDisciplineCodeChange();
  var result = {
    code: vm.selectedDisciplineCode,
    userDefined: false,
    userDefinedDiscipline: null
  };
  expect(vm.selectedDiscipline).toBe(result);
})

Upvotes: 3

Related Questions