[英]QUnit/Sinon: testing a function which checks if cookies are enabled
I have the following (simplified) javascript module which uses jQuery Cookie plugin to check if cookies are enabled. 我有以下(简体)javascript模块,该模块使用jQuery Cookie插件来检查是否启用了cookie。 If cookies are disabled it warns the user:
如果禁用了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>');
}
}
};
})();
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". 测试失败,因为“ cookie已被包装”。 I assume this is because I am mocking $.cookie for both set and read.
我认为这是因为我在嘲笑$ .cookie的设置和读取。 How can I mock the call to $.cookie for both setting and reading in this test?
如何在此测试中模拟设置和读取$ .cookie的调用?
Your assumption is correct. 您的假设是正确的。 Depending on the version of Sinon you're using, you could do something like this:
根据您使用的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();
BTW, it's strange to use Sinon mocks without using .verify()
. 顺便说一句,使用Sinon
.verify()
而不使用.verify()
很奇怪。 Maybe stubs would be a better fit? 也许存根会更适合吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.