有没有办法添加自定义方法来断言chai的接口?

时间:2018-06-13 13:10:33

标签: javascript unit-testing mocha chai

有没有办法添加自定义方法来断言chai的界面?

我试过了:

// test-helper.js

export const testPlugin = function(chai) {
    chai.Assertion.addMethod('customMethod', function() {
      //Something
    })
 }

// abc.test.js

import {assert, use} from 'chai'
import {testPlugin} from 'test-helper.js'

use(testPlugin)

但我认为这只适用于柴的期望界面。 我想将此自定义方法用作assert.customMethod(actual, expected)

如果我在这里遗漏了一些东西,请告诉我。

2 个答案:

答案 0 :(得分:0)

 assert.customMethod = function(actual, expected) {
   //...
};

这称为猴子补丁。

答案 1 :(得分:0)

扩展其他答案...请参见the definition for Chai's assert.equal和其他本机断言以供参考。您的自定义断言可能如下所示:

const chai = require("chai");
chai.assert.assertSpecial = function (actual) {
    // see https://github.com/chaijs/chai/blob/master/lib/chai/assertion.js
    // for Assertion's argument definitions
    const test = new chai.Assertion(null, null, chai.assert, true);
    test.assert(
        actual === "special",
        `expected ${actual} to be "special"`,
        `expected ${actual} to not be "special"`,
        "special",
        actual,
        true);
};
相关问题