摩卡测试 - 解决assertion_error

Mocha test - solving assertion_error

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

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

结果总是 return 错误。因为当您调用 x = new Payment("50.00") 时,它会创建 {name:"50.00", card : undefined, price:undefined}。很明显,我们可以看到没有价格因素。因此它 return 是错误的。这就是我认为你的断言失败的原因。

如果您只想设置价格元素,那么您可以按照 x = new Payment(null,null,"50.00")x = new Payment("","","50.00")