javascript - 即使答案正确,四舍五入到小数点后仍显示错误的功能测试?
问题描述
我的功能是输入华氏温度并将转换输出为摄氏度,或者输入摄氏度并将转换输出为华氏温度。我的测试挑战我将任何结果四舍五入到第一个小数,我做对了。但是我的测试另有说明,我正在使用“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。
似乎在数值结果之后期待某种额外的时间,我不确定为什么会这样。谢谢!
解决方案
您的函数正在返回 a string
,因此只需将您的更新expect
为:
expect(ftoc(100)).toEqual("37.8");
它会起作用。
原因是因为默认.toFixed
返回 a string
,如此处所述。
推荐阅读
- ruby-on-rails - 从 SQLite3 升级到 PG - db 慢 100 倍
- c# - 将 xml 字符串转换为 C# 对象
- java - 如何在Java中找到今天前3个月的开始?
- angularjs - 无法访问我的模板指令中的任何路由
- for-loop - For循环打印出相同的结果
- python - 向flask+sqlalchemy关系列添加过滤器
- python - 构建用于牛眼皮疹识别的卷积神经网络
- node.js - 节点请求实体太大 body-parser 限制设置
- github-api - 在作曲家休息服务器中使用 github 进行身份验证后获取用户数据
- php - CSV文件未加载到mysql数据库中