首页 > 解决方案 > 即使答案正确,四舍五入到小数点后仍显示错误的功能测试?

问题描述

我的功能是输入华氏温度并将转换输出为摄氏度,或者输入摄氏度并将转换输出为华氏温度。我的测试挑战我将任何结果四舍五入到第一个小数,我做对了。但是我的测试另有说明,我正在使用“Jasmine”来测试代码。这就是我所拥有的。

const ftoc = function(fahr) {
  let input = fahr;
  if (typeof fahr === 'number'){
  let result = (fahr - 32) * 5/9;
  if (Number.isInteger(result) === false) {
    return result.toFixed(1);
  } else {return result}
  }
}

const ctof = function(celc) {
  let input = celc;
  if (typeof input === 'number') {
    let result = celc * (9/5) + 32;
    if (Number.isInteger(result) === false) {
    return result.toFixed(1);
    } else {return result}
  }
}

module.exports = {
  ftoc,
  ctof
}

这是测试

const {ftoc, ctof} = require('./tempConversion')

describe('ftoc', function() {
  it('works', function() {
    expect(ftoc(32)).toEqual(0);
  });
  it('rounds to 1 decimal', function() {
    expect(ftoc(100)).toEqual(37.8);
  });
  it('works with negatives', function() {
    expect(ftoc(-100)).toEqual(-73.3);
  });
});

describe('ctof', function() {
  it('works', function() {
    expect(ctof(0)).toEqual(32);
  });
  it('rounds to 1 decimal', function() {
    expect(ctof(73.2)).toEqual(163.8);
  });
  it('works with negatives', function() {
    expect(ctof(-10)).toEqual(14);
  });
});

我的错误如下:预期 '163.8' 等于 163.8。预计“37.8”等于 37.8。预期“-73.3”等于 73.3。

似乎在数值结果之后期待某种额外的时间,我不确定为什么会这样。谢谢!

标签: javascriptfunctionmathdecimalrounding

解决方案


您的函数正在返回 a string,因此只需将您的更新expect为:

expect(ftoc(100)).toEqual("37.8");

它会起作用。

原因是因为默认.toFixed返回 a string,如此所述。


推荐阅读