【问题标题】:How do I extend QUnit with new assertion functions?如何使用新的断言函数扩展 QUnit?
【发布时间】:2013-10-19 22:44:43
【问题描述】:

我想向 QUnit 添加新的断言。 我已经这样做了:

QUnit.extend(QUnit.assert, {
  increases: function(measure, block, message){
    var before = measure();
    block();
    var after = measure();
    var passes = before < after;
    QUnit.push(passes, after, "< " + before, message);
  }
});

当我在测试中使用increases(foo,bar,baz) 时,我得到了

ReferenceError:未定义增加

从浏览器控制台我可以看到increases 与所有其他标准函数一起在QUnit.assert 中找到:okequaldeepEqual 等。

从控制台运行:
test("foo", function(){console.log(ok) });
我看到了ok的来源。

跑步:
test("foo", function(){console.log(increases) });
有人告诉我增加没有定义。

在测试中使用我的增加需要什么魔法?另外,文档在哪里(如果有的话)?

谢谢

【问题讨论】:

    标签: javascript unit-testing qunit


    【解决方案1】:

    我发现解决方案是在测试回调函数中接受一个参数。该参数将具有额外的断言类型。所以我们可以这样称呼它:

    //the assert parameter accepted by the callback will contain the 'increases' assertion
    test("adding 1 increases a number", function(assert){
        var number = 42;
        function measure(){return number;}
        function block(){number += 1;}
        assert.increases(measure, block);
    });
    

    【讨论】:

    • 这是正确的做法。如果您想像其他 QUnit 断言一样通过全局引用使用自定义断言,则必须将其显式添加到全局对象中,通常是 window
    【解决方案2】:

    我今天尝试添加自定义断言,但遇到了同样的问题。 只有原始断言函数也在全局对象中定义。自定义断言不是。

    从调试 QUnit 代码看来,原来的断言函数是有意放置在全局范围 - 窗口变量上的。这发生在 QUnit 的初始化时,所以它只适用于当时已经定义的原始断言函数。

    1.QUnit.js : 原始断言函数的定义

    assert = QUnit.assert = {
      ok: function( result, msg ) {
    
    ...
    

    2.QUnit.js : 原始断言函数 -> QUnit.constructor.prototype

    extend( QUnit.constructor.prototype, assert );
    

    3.QUnit.js : QUnit.constructor.prototype -> 窗口

    // For browser, export only select globals
    if ( typeof window !== "undefined" ) {
        extend( window, QUnit.constructor.prototype );
        window.QUnit = QUnit;
    }
    

    解决方案

    所以正如您所回答的,为了使用自定义断言功能,需要:

    1. 捕获传递给每个断言函数的assert 参数并使用它。 前任。

      test("test name", function(assert) {
        assert.cosutomAssertion(..); 
      ...});
      
    2. 或者使用完整的命名空间来访问断言函数。 前任。

      QUnit.assert.customAssertion(..)
      

    【讨论】:

      猜你喜欢
      • 2012-04-28
      • 2013-01-09
      • 1970-01-01
      • 1970-01-01
      • 2012-10-04
      • 2018-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多