我有以下(简化的) 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的调用以进行设置和读取?
发布于 2014-12-08 19:19:30
你的假设是正确的。根据您使用的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();顺便说一句,不使用.verify()就使用Sinon模拟是很奇怪的。或许存根会更合适?
https://stackoverflow.com/questions/26732523
复制相似问题