有什么方法可以向chai的assert接口添加自定义方法?

8
有没有办法向chai的assert接口添加自定义方法?
我尝试过以下代码:
// 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)

但我认为这只适用于chai的expect接口。

我想使用自定义方法,如assert.customMethod(actual, expected)

如果我漏掉了什么,请告诉我。

2个回答

3

扩展其他答案...请参考Chai的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);
};

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

这被称为猴子补丁。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接