【问题标题】:Is there any way to add custom methods to assert interface of chai?有没有办法添加自定义方法来断言 chai 的接口?
【发布时间】:2018-06-13 13:10:32
【问题描述】:

有什么方法可以添加自定义方法来断言 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)

但我认为这只适用于 chai 的 expect 接口。 我想将此自定义方法用作assert.customMethod(actual, expected)

如果我在这里遗漏了什么,请告诉我。

【问题讨论】:

    标签: javascript unit-testing mocha.js chai


    【解决方案1】:

    扩展其他答案...查看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);
    };
    

    【讨论】:

      【解决方案2】:
       assert.customMethod = function(actual, expected) {
         //...
      };
      

      这称为猴子补丁。

      【讨论】:

        猜你喜欢
        • 2021-04-01
        • 1970-01-01
        • 2017-08-21
        • 1970-01-01
        • 2020-11-13
        • 2012-11-03
        • 1970-01-01
        • 1970-01-01
        • 2019-11-28
        相关资源
        最近更新 更多