业力覆盖不识别分支测试

Karma-coverage not recognizing branch test

我的 karma-coverage 报告指出我的 'else' 分支没有包含在下面的示例中,但它已经过测试。为什么 karma-coverage 无法识别我的测试有什么想法吗?

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!');
  });
});

实际上业力覆盖是正确的。您错过了测试 else 分支的机会。

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!' );
} );} );

考虑到您的 utilities.service.js 是

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

return valueFormatted + '!';}

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

return valueFormatted + '!';}