简体   繁体   中英

Karma-coverage not recognizing branch test

My karma-coverage report states that my 'else' branch is not covered in the below example, but it is tested. Any ideas why karma-coverage is not recognizing my test?

utilities.service.js:

function formatValue(value, form) {

  if (form === '2') {
    valueFormatted = twoDecimals(value);
  } else if (form === '4') {
    valueFormatted = fourDecimals(value);
  }

  return valueFormatted + '!';
}

utilitiesServiceSpec.js:

describe('format values', function() {
  var formattedValue;
  var value;
  var form;

  it('should format 2 decimal places', function() {
    value = 100;
    form = '2';
    formattedValue = utilitiesService.formatValue(value, form);
    expect(formattedValue).toEqual('100.00!');
  });

  it('should format 4 decimal places', function() {
    value = 100;
    form = '4';
    formattedValue = utilitiesService.formatValue(value, form);
    expect(formattedValue).toEqual('100.0000!');
  });
});

Actually karma-coverage is correct. You missed to test the else branch.

describe( 'format values', function() {
var formattedValue;
var value;
var form;
// Will test if (form === '2')
it( 'should format 2 decimal places', function() {
    value = 100;
    form = '2';
    formattedValue = utilitiesService.formatValue( value, form );
    expect( formattedValue ).toEqual( '100.00!' );
} );

// Will test else if (form === '4')
it( 'should format 4 decimal places', function() {
    value = 100;
    form = '4';
    formattedValue = utilitiesService.formatValue( value, form );
    expect( formattedValue ).toEqual( '100.0000!' );
} );
//Will test else
it( 'should test if value should not be formatted to decimal if form is other than 2 and 4', function() {
    value = 100;
    form = '5';
    formattedValue = utilitiesService.formatValue( value, form );
    expect( formattedValue ).toEqual( '100!' );
} );} );

Considering your utilities.service.js to be

function formatValue( value, form ) {
var valueFormatted = value;
if ( form === '2' ) {
    valueFormatted = twoDecimals( value );
} else if ( form === '4' ) {
    valueFormatted = fourDecimals( value );
}

return valueFormatted + '!';}

or

function formatValue( value, form ) {
var valueFormatted;
if ( form === '2' ) {
    valueFormatted = twoDecimals( value );
} else if ( form === '4' ) {
    valueFormatted = fourDecimals( value );
} else {
    valueFormatted = value;
}

return valueFormatted + '!';}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM