我正在练习使用Mocha和classes。我正在写一些测试,这些测试都是成功的,直到我遇到一个断言错误,这是我仍然不太熟悉的东西。
我的test.js文件如下所示,从几个类开始:
var assert = require('assert');
class Payment
{
constructor (name,card,price)
{
this.name = name;
this.card = card;
this.price = price;
}
}
class BillingService
{
processPayment(payment)
{
if(payment.card == "123"){return true;}
else{return false;}
}
checkName(payment)
{
if(payment.name == "John B"){return true;}
else{return false;}
}
checkTotal(payment)
{
if(payment.price == "50.00"){return true;}
else{return false;}
}
}接下来,我开始我的测试:
describe('BillingService', function()
{
it('should process payment', function()
{
var x = new Payment("John B", "123", "50.00");
var billingService = new BillingService();
var outcome = billingService.processPayment(x);
assert.equal(true, outcome);
});
it('should not process payment', function()
{
var x = new Payment("John B", "xf23", "50.00");
var billingService = new BillingService();
var outcome = billingService.processPayment(x);
assert.equal(false, outcome);
});
it('should get name', function()
{
var x = new Payment("John B");
var billingService = new BillingService();
var outcome = billingService.checkName(x);
assert.equal(true, outcome);
});
it('should not get name', function()
{
var x = new Payment("Scarlett");
var billingService = new BillingService();
var outcome = billingService.checkName(x);
assert.equal(false, outcome);
});
it('should return price', function()
{
var x = new Payment("50.00");
var billingService = new BillingService();
var outcome = billingService.checkTotal(x);
assert.equal(true, outcome);
});
it('should not return price', function()
{
var x = new Payment("23.00");
var billingService = new BillingService();
var outcome = billingService.checkTotal(x);
assert.equal(false, outcome);
});
}此时,我可以运行"mocha test“命令并开始测试。
如上所述,我取得了成功。然后,我收到了以下消息:
BillingService
✓ should process payment
✓ should not process payment
✓ should get name
✓ should not get name
1) should return price
✓ should not return price
5 passing (11ms)
1 failing
1) BillingService
should return price:
AssertionError [ERR_ASSERTION]: true == false
+ expected - actual
-true
+false
at Context.<anonymous> (test.js:130:12)基本上,我正在尝试找出为什么会出现断言错误并修复它。
发布于 2019-04-30 12:04:49
如果你这样做的话
it('should return price', function()
{
var x = new Payment("50.00");
var billingService = new BillingService();
var outcome = billingService.checkTotal(x);
assert.equal(true, outcome);
});它总是返回false作为结果。因为当您调用x = new Payment("50.00")时,它会创建{name:"50.00", card : undefined, price:undefined}。因此,很明显,我们可以看到没有价格元素。因此,它返回false。我想这就是你的断言失败的原因。
如果只想设置价格元素,则可以像x = new Payment(null,null,"50.00")或x = new Payment("","","50.00")那样进行设置
https://stackoverflow.com/questions/55913614
复制相似问题