![](/img/trans.png)
[英]Testing function which checks if cookies are enabled with Qunit
[英]QUnit/Sinon: testing a function which checks if cookies are enabled
我有以下(简体)javascript模块,该模块使用jQuery Cookie插件来检查是否启用了cookie。 如果禁用了cookie,则会警告用户:
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的调用?
您的假设是正确的。 根据您使用的Sinon版本,您可以执行以下操作:
// 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();
顺便说一句,使用Sinon .verify()
而不使用.verify()
很奇怪。 也许存根会更适合吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.