isTriangle
函数检查三角形的边并确定三角形是斜角,等边还是等腰。
编写函数后,我需要通过Jasmine和Javascript进行单元测试。
代码:
function isTriangleTranslate(side1, side2, side3) {
if (side1 === side2 && side3 === side2 && side2 === side1) {
return ("It's an equilateral!");
}
if (side2 === side3 && side1 != side2 && side1 != side3 || side1 === side3 && side2 != side1 && side2 != side3 || side1 === side2 && side2 != side3) {
return ("It's an isosceles!");
}
else {
return ("It's a scalene!");
}
}
规格:
describe("isTriangle", function(){
it("is an equilateral trinagle with three equal sides", function(){
expect(isTriangleTranslate()).toEqual("It's an equilateral!");
})
});
describe("isTriangle", function(){
it("is an isosceles triangle with two equal sides", function(){
expect(isTriangleTranslate()).toEqual("It's an isosceles!");
})
});
describe("isTriangle", function(){
it("is a scalene triangle with no equal sides", function(){
expect(isTriangleTranslate()).toEqual("It's a scalene!");
})
});
错误是,斜角肌和等腰肌不等于“这是等边的”
我不希望它那样做。我要它确定我的side1,side2和side3是否相等,然后等于字符串“这是等边的!”
如果我的side1,side2和side3的两个边相等,则等于字符串“这是一个等腰!”
否则,三角形是“这是一个斜角!”
您将如何在Jasmine的单元测试中编写此代码?
答案 0 :(得分:0)
首先,我将根据一般原则简化该功能:
function isTriangleTranslate(a, b, c) {
if (a === b && b === c && c === a) {
return ("It's an equilateral!")
}
else if (a+b == a+c || b+a == b+c || c+a == c+b) {
return ("It's an isosceles!");
} else {
return ("It's a scalene!");
}
}
然后,我将值传递给测试。您只是在调用不带参数的方法。
describe("isTriangle", function(){
it("is an equilateral triangle with three equal sides", function(){
expect(isTriangleTranslate(4,4,4)).toEqual("It's an equilateral!");
})
});
describe("isTriangle", function(){
it("is an isosceles triangle with two equal sides", function(){
expect(isTriangleTranslate(4,4,5)).toEqual("It's an isosceles!");
})
});
describe("isTriangle", function(){
it("is a scalene triangle with no equal sides", function(){
expect(isTriangleTranslate(4,5,6)).toEqual("It's a scalene!");
})
});