如何在Mocha中实现addMatchers?

时间:2015-09-17 14:25:14

标签: coffeescript jasmine mocha chai

我正在使用使用Jasmine教授BDD的CoffeScript测试书,但我正在使用Mocha / Chai,并且遇到了这段代码:

beforeEach -> 
  @addMatchers  
    toBeDiscounted: (orig,discount) ->  
      actual = @actual  
      @message = -> "Expected #{actual} to be #{discount}% of #{orig}"  
      actual is (orig * (1-(discount/100)))  

然后在测试中:

it "should persist the discount", ->  
  expect(test.basket.applyDiscount(10)).toBeDiscounted(50, 10)  

我如何在Mocha / Chai中这样做?

1 个答案:

答案 0 :(得分:1)

Jasmine matchers相当于Mocha / Chai土地中的 Chai Helpers 。 您需要更新规范帮助程序以包含Custom Chai Helper。然后,你需要写Chai Helper本身;使它扩展Chai以添加discounted函数。

规格/ SPEC-helper.js

var chai = require('chai');

var chaiDiscounted = require('./helpers/discounted.js')
chai.use(chaiDiscounted);

规格/助手/ discounted.js

function discount(x, discount) {
  return x * (1 - (discount / 100));
}

module.exports = function(chai) {
  var Assertion = chai.Assertion;

  Assertion.addMethod('discounted', function (y, p) {
    var obj = this._obj;
    new Assertion(obj).to.be.a('number');
    this.assert(
        obj === discount(y, p)
      , "expected #{this} to be " + y + "% of " + p
      , "expected #{this} to not be " + y + "% of " + p
    );
  });
}

然后您应该能够:

expect(foo).to.be.discounted(50, 10)

抱歉,我没有测试过这个。另外,我很抱歉这是Javascript(不是Coffeescript)......但希望它能帮助你找到正确的方向。