gpt4 book ai didi

javascript - Mocha测试-解决assertion_error

转载 作者:行者123 更新时间:2023-12-02 23:44:31 25 4
gpt4 key购买 nike

我正在练习使用 Mocha 和类(class)。我正在编写一些成功的测试,直到遇到断言错误,这是我仍然不太熟悉的事情。

我的 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)

基本上,我试图找出为什么会出现断言错误并修复它。

最佳答案

如果你喜欢这个

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")

关于javascript - Mocha测试-解决assertion_error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55913614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com