QUnit/Sinon:测试一个功能,该功能检查是否启用了cookie [英] QUnit/Sinon: testing a function which checks if cookies are enabled

查看:115
本文介绍了QUnit/Sinon:测试一个功能,该功能检查是否启用了cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下(简体)javascript模块,该模块使用jQuery Cookie插件来检查是否启用了cookie.如果Cookie被禁用,则会警告用户:

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>');
            }
        }
    };
})();

我有以下单元测试:

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!");
});

测试失败,因为"cookie已被包装".我认为这是因为我在嘲笑$ .cookie的设置和读取.在该测试中,如何设置和读取对$ .cookie的调用?

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?

推荐答案

您的假设是正确的.根据您使用的Sinon版本,您可以执行以下操作:

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();

顺便说一句,在不使用.verify()的情况下使用Sinon模拟是很奇怪的.也许存根会更合适?

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

这篇关于QUnit/Sinon:测试一个功能,该功能检查是否启用了cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆