blob: df4284ab7f9f074f924b47c4dd3701e7f16ebb07 [file] [log] [blame]
<!DOCTYPE html>
<!--
Copyright 2015 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<script>
'use strict';
var testing_common = (function() {
var fixture = null;
var xhrMock = null;
var XMLHttpRequestMock = function() {
this.responseMap_ = {};
window.XMLHttpRequest = this.getMock();
};
XMLHttpRequestMock.prototype.getMock = function() {
// TODO(chrisphan): Add support for error state.
var self = this;
return function() {
this.status = 200;
this.onerror = function() {};
this.open = function(method, url, async) {
this.url = url;
};
this.abort = function() {};
this.setRequestHeader = function() {};
this.onload = function() {};
this.send = function(param) {
var requestStr = this.url + '?' + param;
if (requestStr in self.responseMap_) {
this.responseText = self.responseMap_[requestStr];
this.onload();
} else {
console.warn('XMLHttpRequest sent without a handler: ' + requestStr);
}
};
};
};
XMLHttpRequestMock.prototype.add = function(param, response) {
this.responseMap_[param] = response;
};
function addXhrMock(param, response) {
if (!xhrMock) {
xhrMock = new XMLHttpRequestMock();
}
xhrMock.add(param, response);
};
function clearXhrMock() {
// Reverts back to native XMLHttpRequest.
delete window.XMLHttpRequest;
xhrMock = null;
};
/**
* Does a deep copy of the object.
* @param {*} obj Object to copy.
* @return {*} A copy of the object.
*/
function deepCopy(obj) {
return JSON.parse(JSON.stringify(obj));
};
function addToFixture(node) {
if (!fixture) {
fixture = document.createElement('div');
document.body.appendChild(fixture);
}
fixture.appendChild(node);
};
function clearFixture() {
if (fixture) {
fixture.innerHTML = '';
}
};
return {
addXhrMock: addXhrMock,
clearXhrMock: clearXhrMock,
deepCopy: deepCopy,
addToFixture: addToFixture,
clearFixture: clearFixture
};
})();
</script>