【问题标题】:Why is qunit test returning wrong value为什么 qunit 测试返回错误值
【发布时间】:2020-12-14 13:57:02
【问题描述】:

我有以下功能:

MarketingHandler = function () {
    return {
        Init: function () {

                $(document).on("click", "#verify .modal-close", function () {
                    tryVerification();
                });


        }

    }

    function tryCommunicationPreferencesInterceptorAfterVerification() {
        var overlayIsNotDismissed = CookieHelper.GetCookie("dismissed-overlay") == null

        if (overlayIsNotDismissed && window.location.pathname === "/Home/") {
            OverlayHelper.Display("save-preferences");
        }
        else if (overlayIsNotDismissed) {
            // do something else 
        }
    }
}();

$(document).ready(function () {
    MarketingHandler.Init();
});

我正在尝试编写一个测试,显示应该调用OverlayHelper.Display("save-preferences");。这是我的尝试:

QUnit.test("Test", function (assert) {
    MarketingHandler.Init();
    if (CookieHelper.GetCookie("dismissed-overlay") != null) {
        CookieHelper.DeleteCookie("dismissed-overlay");
    }

    sinon.stub(window.location, 'pathname').returns("/Home/");
    var displayOverlaySpy = sinon.spy(OverlayHelper, 'Display');

    var $fixture = $("#qunit-fixture");
    $fixture.append(HTMLInjector());
    $('#verify .modal-close').click();

    assert.ok(displayOverlaySpy.calledOnceWith("save-preferences"), "overlay shown");
    displayOverlaySpy.restore();
});

function HTMLInjector() {
    return "<input type='hidden' id='verify .modal-close'/>"
}

但是,我在测试中得到“预期为真,结果为假”。谁能发现我在这里出错的地方?

【问题讨论】:

  • 想知道您是否调用了两次Init() 可能与此有关...哦,还有,tryVerification 方法不存在?应该是tryCommunicationPreferencesInterceptorAfterVerification 吗?

标签: javascript unit-testing sinon qunit


【解决方案1】:

似乎点击事件是异步触发的,并且断言发生在点击发生之前。我认为您可以使用以下方法来解决此问题。

var done = assert.async();
var $fixture = $("#qunit-fixture");
$fixture.append(HTMLInjector());
$('#verify .modal-close').click();

setTimeout(function() {
    assert.ok(displayOverlaySpy.calledOnceWith("save-preferences"), "overlay shown");
    done();
});

【讨论】:

  • 感谢您的建议,但这导致“测试时间超过 30000 毫秒;测试超时。” @ZeninEasaPanthakkalakath
  • 您能否添加一个断点并手动验证事情是否按照您的意图进行?例如,某些变量或函数可能在测试中未定义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-28
相关资源
最近更新 更多