Karma-coverage不承认分支测试

时间:2015-07-13 15:40:10

标签: javascript angularjs unit-testing jasmine karma-runner

我的业力报道报告指出我的“其他”分支未在下面的示例中介绍,但已经过测试。任何想法为什么业力覆盖不承认我的测试?

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

1 个答案:

答案 0 :(得分:4)

实际上业力覆盖是正确的。你错过了测试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 + '!';}