QUnit/Sinon: testing a function which checks if cookies are enabled

蹲街弑〆低调 提交于 2019-12-12 02:07:28

问题


I have the following (simplified) javascript module which uses jQuery Cookie plugin to check if cookies are enabled. If cookies are disabled it warns the user:

var cookiePolicy = (function () {
    var cookiesEnabled = function () {
        return $.cookie('check', 'valid', { expires: 1 }) && $.cookie('check') == 'valid';
    };

    return {
        updateCookiePolicy: function () {
            if (!cookiesEnabled()) {
                $("#cookie-policy").append('<p id="cookie-warning">Cookies are disabled. Some features of this site may not work correctly.</p>');
            }
        }
    };
})();

I have the following unit test:

QUnit.test("When cookies are enabled the cookie policy text remains unchanged", function (assert) {
    sinon.mock($).expects("cookie").once().withExactArgs("check", "valid", { expires: 1 });
    sinon.mock($).expects("cookie").once().withExactArgs("check").returns("valid");

    cookiePolicy.updateCookiePolicy();

    assert.equal(0, $('#cookie-warning').length, "Failed!");
});

The test fails because "cookie is already wrapped". I assume this is because I am mocking $.cookie for both set and read. How can I mock the call to $.cookie for both setting and reading in this test?


回答1:


Your assumption is correct. Depending on the version of Sinon you're using, you could do something like this:

// UUT
var foo = {
    bar: function() {}
};

// Test setup
var mock = sinon.mock(foo);
var expectation = mock.expects('bar').twice();
expectation.onFirstCall().stub.calledWithExactly('baz');
expectation.onSecondCall().stub.calledWithExactly('qux');

// Test
foo.bar('baz');
foo.bar('qux');
mock.verify();

BTW, it's strange to use Sinon mocks without using .verify(). Maybe stubs would be a better fit?



来源:https://stackoverflow.com/questions/26732523/qunit-sinon-testing-a-function-which-checks-if-cookies-are-enabled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!