如何在单元测试中使用Sinon更改属性值?

时间:2017-05-29 15:22:48

标签: jquery unit-testing sinon qunit

我有这段代码:

AlertHelper = function () {
    return {
        DisplayToastMessage: function() {
            if ($("body > .modal.small").length > 1) {
                AlertHelper.CalculateAdditionalHeight();
            }
        }
    }
}();

我尝试用QUnit和SinonJS编写单元测试。

这是单元测试:

QUnit.test('DisplayToastMessage - testing function call', function (assert) {
    var sandbox = sinon.sandbox.create();
    var mock = sinon.mock(AlertHelper);

    sandbox.stub($("body > .modal.small"), "length", 42);

    var expectationCalculateAdditionalHeight = mock.expects("CalculateAdditionalHeight");
    expectationCalculateAdditionalHeight.once();

    AlertHelper.DisplayToastMessage();

    mock.verify();
    assert.ok(mock.verify(), "CalculateAdditionalHeight function is called once");

    sandbox.restore();
    mock.restore();
});

但是我收到错误“无法读取未定义的属性'长度'”。 如何测试是否调用了CalculateAdditionalHeight函数?

2 个答案:

答案 0 :(得分:0)

尝试模拟实例:

$ = sinon.stub(); $.withArgs('body > .modal.small').returns({"length": 42});

答案 1 :(得分:0)

经过研究,我找到了解决方案:

<div class="col-sm-6">
    <a id="tester" data-toggle="collapse" href="#collapsible" aria-expanded="false">
        <h3><span class="glyphicon glyphicon-star"></span> Extra <span id="testerTwo" class="glyphicon glyphicon-eye-close"></span></h3>
    </a>
    <div class="collapse" id="collapsible">
        <div class="card card-block">
            <ul>
                <li><a href="#">item 1</a></li>
                <li><a href="#">item 2</a></li>
                <li><a href="#">item 3</a></li>
                <li><a href="#">item 4</a></li>
            </ul>
        </div>
    </div>
</div>