webdriverajax
Advanced tools
Comparing version 2.2.0 to 3.0.0-beta.1
336
index.js
'use strict'; | ||
var interceptor = require('./lib/interceptor'); | ||
const interceptor = require('./lib/interceptor'); | ||
function plugin (wdInstance, options) { | ||
function plugin(wdInstance, options) { | ||
/** | ||
* instance need to have addCommand method | ||
*/ | ||
if (typeof wdInstance.addCommand !== 'function') { | ||
throw new Error( | ||
"you can't use WebdriverAjax with this version of WebdriverIO" | ||
); | ||
} | ||
/** | ||
* instance need to have addCommand method | ||
*/ | ||
if (typeof wdInstance.addCommand !== 'function') { | ||
throw new Error('you can\'t use WebdriverAjax with this version of WebdriverIO'); | ||
} | ||
wdInstance.addCommand('setupInterceptor', setup.bind(wdInstance)); | ||
wdInstance.addCommand('expectRequest', expectRequest.bind(wdInstance)); | ||
wdInstance.addCommand('assertRequests', assertRequests.bind(wdInstance)); | ||
wdInstance.addCommand('getRequest', getRequest.bind(wdInstance)); | ||
wdInstance.addCommand('getRequests', getRequest.bind(wdInstance)); | ||
wdInstance.addCommand('setupInterceptor', setup.bind(wdInstance)); | ||
wdInstance.addCommand('expectRequest', expectRequest.bind(wdInstance)); | ||
wdInstance.addCommand('assertRequests', assertRequests.bind(wdInstance)); | ||
wdInstance.addCommand('getRequest', getRequest.bind(wdInstance)); | ||
wdInstance.addCommand('getRequests', getRequest.bind(wdInstance)); | ||
function setup() { | ||
wdInstance.__wdajaxExpectations = []; | ||
return wdInstance.executeAsync(interceptor.setup); | ||
} | ||
function setup () { | ||
wdInstance.__wdajaxExpectations = []; | ||
return wdInstance.executeAsync(interceptor.setup); | ||
} | ||
function expectRequest(method, url, statusCode) { | ||
wdInstance.__wdajaxExpectations.push({ | ||
method: method.toUpperCase(), | ||
url: url, | ||
statusCode: statusCode | ||
}); | ||
return {}; | ||
} | ||
function expectRequest (method, url, statusCode) { | ||
wdInstance.__wdajaxExpectations.push({ | ||
method: method.toUpperCase(), | ||
url: url, | ||
statusCode: statusCode | ||
}); | ||
return {}; | ||
function assertRequests() { | ||
const expectations = wdInstance.__wdajaxExpectations; | ||
if (!expectations.length) { | ||
return Promise.reject( | ||
new Error('No expectations found. Call .expectRequest() first') | ||
); | ||
} | ||
return getRequest().then(requests => { | ||
if (expectations.length !== requests.length) { | ||
return Promise.reject( | ||
new Error( | ||
'Expected ' + | ||
expectations.length + | ||
' requests but was ' + | ||
requests.length | ||
) | ||
); | ||
} | ||
function assertRequests () { | ||
for (let i = 0; i < expectations.length; i++) { | ||
const ex = expectations[i]; | ||
const request = requests[i]; | ||
var expectations = wdInstance.__wdajaxExpectations; | ||
if (request.method !== ex.method) { | ||
return Promise.reject( | ||
new Error( | ||
'Expected request to URL ' + | ||
request.url + | ||
' to have method ' + | ||
ex.method + | ||
' but was ' + | ||
request.method | ||
) | ||
); | ||
} | ||
if ( | ||
ex.url instanceof RegExp && | ||
request.url && | ||
!request.url.match(ex.url) | ||
) { | ||
return Promise.reject( | ||
new Error( | ||
'Expected request ' + | ||
i + | ||
' to match ' + | ||
ex.url.toString() + | ||
' but was ' + | ||
request.url | ||
) | ||
); | ||
} | ||
if (!expectations.length) { | ||
return Promise.reject(new Error( | ||
'No expectations found. Call .expectRequest() first' | ||
)); | ||
if (typeof ex.url == 'string' && request.url !== ex.url) { | ||
return Promise.reject( | ||
new Error( | ||
'Expected request ' + | ||
i + | ||
' to have URL ' + | ||
ex.url + | ||
' but was ' + | ||
request.url | ||
) | ||
); | ||
} | ||
return getRequest().then(function assertAllRequests (requests) { | ||
if (expectations.length !== requests.length) { | ||
return Promise.reject(new Error( | ||
'Expected ' + | ||
expectations.length + | ||
' requests but was ' + | ||
requests.length | ||
)); | ||
} | ||
if (request.response.statusCode !== ex.statusCode) { | ||
return Promise.reject( | ||
new Error( | ||
'Expected request to URL ' + | ||
request.url + | ||
' to have status ' + | ||
ex.statusCode + | ||
' but was ' + | ||
request.response.statusCode | ||
) | ||
); | ||
} | ||
} | ||
for (var i = 0; i < expectations.length; i++) { | ||
var ex = expectations[i]; | ||
var request = requests[i]; | ||
return wdInstance; | ||
}); | ||
} | ||
if (request.method !== ex.method) { | ||
return Promise.reject(new Error( | ||
'Expected request to URL ' + | ||
request.url + | ||
' to have method ' + | ||
ex.method + | ||
' but was ' + request.method | ||
)); | ||
} | ||
function getRequest(index) { | ||
return wdInstance.execute(interceptor.getRequest, index).then(request => { | ||
if (!request.value) { | ||
if (index != null) { | ||
return Promise.reject( | ||
new Error('Could not find request with index ' + index) | ||
); | ||
} | ||
return []; | ||
} | ||
if (Array.isArray(request.value)) { | ||
return request.value.map(transformRequest); | ||
} | ||
// The edge driver does not seem to typecast arrays correctly | ||
if (typeof request.value[0] == 'object') { | ||
return mapIndexed(request.value, transformRequest); | ||
} | ||
return transformRequest(request.value); | ||
}); | ||
} | ||
if (ex.url instanceof RegExp && request.url && !request.url.match(ex.url)) { | ||
return Promise.reject(new Error( | ||
'Expected request ' + | ||
i + | ||
' to match ' | ||
+ ex.url.toString() + | ||
' but was ' + | ||
request.url | ||
)); | ||
} | ||
if (typeof ex.url == 'string' && request.url !== ex.url) { | ||
return Promise.reject(new Error( | ||
'Expected request ' + | ||
i + | ||
' to have URL ' | ||
+ ex.url + | ||
' but was ' + | ||
request.url | ||
)); | ||
} | ||
if (request.response.statusCode !== ex.statusCode) { | ||
return Promise.reject(new Error( | ||
'Expected request to URL ' + | ||
request.url + | ||
' to have status ' + | ||
ex.statusCode + | ||
' but was ' + | ||
request.response.statusCode | ||
)); | ||
} | ||
} | ||
return wdInstance; | ||
}); | ||
function transformRequest(req) { | ||
if (!req) { | ||
return; | ||
} | ||
function getRequest (index) { | ||
return wdInstance.execute(interceptor.getRequest, index) | ||
.then(function (request) { | ||
if (!request.value) { | ||
const message = index ? 'Could not find request with index ' + index : 'No requests captured'; | ||
return Promise.reject(new Error(message)); | ||
} | ||
if (Array.isArray(request.value)) { | ||
return request.value.map(transformRequest); | ||
} | ||
// The edge driver does not seem to typecast arrays correctly | ||
if (typeof request.value[0] == 'object') { | ||
return mapIndexed(request.value, transformRequest); | ||
} | ||
return transformRequest(request.value); | ||
}); | ||
} | ||
return { | ||
url: req.url, | ||
method: req.method && req.method.toUpperCase(), | ||
body: parseBody(req.requestBody), | ||
headers: normalizeRequestHeaders(req.requestHeaders), | ||
response: { | ||
headers: parseResponseHeaders(req.headers), | ||
body: parseBody(req.body), | ||
statusCode: req.statusCode | ||
} | ||
}; | ||
} | ||
function transformRequest (req) { | ||
if (!req) { | ||
return; | ||
} | ||
function normalizeRequestHeaders(headers) { | ||
const normalized = {}; | ||
Object.keys(headers).forEach(key => { | ||
normalized[key.toLowerCase()] = headers[key]; | ||
}); | ||
return normalized; | ||
} | ||
return { | ||
url: req.url, | ||
method: req.method && req.method.toUpperCase(), | ||
body: parseBody(req.requestBody), | ||
headers: normalizeRequestHeaders(req.requestHeaders), | ||
response: { | ||
headers: parseResponseHeaders(req.headers), | ||
body: parseBody(req.body), | ||
statusCode: req.statusCode | ||
} | ||
}; | ||
} | ||
function parseResponseHeaders(str) { | ||
const headers = {}; | ||
const arr = str | ||
.trim() | ||
.replace(/\r/g, '') | ||
.split('\n'); | ||
arr.forEach(header => { | ||
const match = header.match(/^(.+)?:\s?(.+)$/); | ||
if (match) { | ||
headers[match[1].toLowerCase()] = match[2]; | ||
} | ||
}); | ||
return headers; | ||
} | ||
function normalizeRequestHeaders (headers) { | ||
var normalized = {}; | ||
Object.keys(headers).forEach(function (key) { | ||
normalized[key.toLowerCase()] = headers[key]; | ||
}); | ||
return normalized; | ||
function parseBody(str) { | ||
let body; | ||
try { | ||
body = JSON.parse(str); | ||
} catch (e) { | ||
body = str; | ||
} | ||
return body; | ||
} | ||
function parseResponseHeaders (str) { | ||
var headers = {}; | ||
var arr = str.trim().replace(/\r/g, '').split('\n'); | ||
arr.forEach(function (header) { | ||
var match = header.match(/^(.+)?:\s?(.+)$/); | ||
if (match) { | ||
headers[match[1].toLowerCase()] = match[2]; | ||
} | ||
}); | ||
return headers; | ||
// maps an 'array-like' object. returns proper array | ||
function mapIndexed(obj, fn) { | ||
const arr = []; | ||
const max = Math.max.apply(Math, Object.keys(obj).map(Number)); | ||
for (let i = 0; i <= max; i++) { | ||
arr.push(fn(obj[i], i)); | ||
} | ||
function parseBody (str) { | ||
var body; | ||
try { | ||
body = JSON.parse(str); | ||
} catch (e) { | ||
body = str; | ||
} | ||
return body; | ||
} | ||
// maps an 'array-like' object. returns proper array | ||
function mapIndexed (obj, fn) { | ||
var arr = []; | ||
var max = Math.max.apply(Math, Object.keys(obj).map(Number)); | ||
for (var i = 0; i <= max; i++) { | ||
arr.push(fn(obj[i], i)); | ||
} | ||
return arr; | ||
} | ||
return arr; | ||
} | ||
} | ||
@@ -190,2 +206,2 @@ | ||
*/ | ||
module.exports.init = plugin; | ||
exports.init = plugin; |
'use strict'; | ||
var interceptor = { | ||
setup: function setup (done) { | ||
setup: function setup(done) { | ||
var NAMESPACE = '__webdriverajax'; | ||
var NAMESPACE = '__webdriverajax'; | ||
window[NAMESPACE] = { requests: [] }; | ||
window[NAMESPACE] = { requests: [] }; | ||
// Some browsers don't support FormData.entries(), so we polyfill that (sigh) | ||
if (typeof FormData.prototype.entries == 'undefined') { | ||
polyfillFormDataEntries(); | ||
} | ||
// Some browsers don't support FormData.entries(), so we polyfill that (sigh) | ||
if (typeof FormData.prototype.entries == 'undefined') { | ||
polyfillFormDataEntries(); | ||
var _XHR = window.XMLHttpRequest; | ||
window.XMLHttpRequest = function() { | ||
var xhr = new _XHR(); | ||
var originalOpen = xhr.open; | ||
var originalSend = xhr.send; | ||
var originalSetRequestHeader = xhr.setRequestHeader; | ||
var lastMethod; | ||
var lastURL; | ||
var lastRequestBody; | ||
var lastRequestHeader = {}; | ||
xhr.open = function() { | ||
lastMethod = arguments[0]; | ||
lastURL = arguments[1]; | ||
originalOpen.apply(xhr, arguments); | ||
}; | ||
xhr.send = function() { | ||
var payload; | ||
if (typeof arguments[0] == 'string') { | ||
payload = arguments[0]; | ||
} else if (arguments[0] instanceof FormData) { | ||
payload = {}; | ||
for (var entry of arguments[0].entries()) { | ||
payload[entry[0]] = entry.slice(1); | ||
} | ||
payload = JSON.stringify(payload); | ||
} else if (arguments[0] instanceof ArrayBuffer) { | ||
payload = String.fromCharCode.apply(null, arguments[0]); | ||
} else { | ||
// Just try to convert it to a string, whatever it might be | ||
try { | ||
payload = JSON.stringify(arguments[0]); | ||
} catch (e) { | ||
payload = ''; | ||
} | ||
} | ||
var _XHR = window.XMLHttpRequest; | ||
window.XMLHttpRequest = function () { | ||
var xhr = new _XHR(); | ||
var originalOpen = xhr.open; | ||
var originalSend = xhr.send; | ||
var originalSetRequestHeader = xhr.setRequestHeader; | ||
var lastMethod; | ||
var lastURL; | ||
var lastRequestBody; | ||
var lastRequestHeader = {}; | ||
xhr.open = function () { | ||
lastMethod = arguments[0]; | ||
lastURL = arguments[1]; | ||
originalOpen.apply(xhr, arguments); | ||
}; | ||
xhr.send = function () { | ||
var payload; | ||
if (typeof arguments[0] == 'string') { | ||
payload = arguments[0]; | ||
} else if (arguments[0] instanceof FormData) { | ||
payload = {}; | ||
for (var entry of arguments[0].entries()) { | ||
payload[entry[0]] = entry.slice(1); | ||
} | ||
payload = JSON.stringify(payload); | ||
} else if (arguments[0] instanceof ArrayBuffer) { | ||
payload = String.fromCharCode.apply(null, arguments[0]); | ||
} else { | ||
// Just try to convert it to a string, whatever it might be | ||
try { | ||
payload = JSON.stringify(arguments[0]); | ||
} catch (e) { | ||
payload = ''; | ||
} | ||
} | ||
lastRequestBody = payload; | ||
originalSend.apply(xhr, arguments); | ||
}; | ||
xhr.setRequestHeader = function() { | ||
lastRequestHeader[arguments[0]] = arguments[1]; | ||
originalSetRequestHeader.apply(xhr, arguments); | ||
}; | ||
xhr.addEventListener('load', function () { | ||
var req = { | ||
url: lastURL, | ||
method: lastMethod.toUpperCase(), | ||
headers: xhr.getAllResponseHeaders(), | ||
requestHeaders: lastRequestHeader, | ||
// IE9 comp: need xhr.responseText | ||
body: xhr.response || xhr.responseText, | ||
statusCode: xhr.status, | ||
requestBody: lastRequestBody, | ||
}; | ||
window[NAMESPACE].requests.push(req); | ||
if (window.sessionStorage && window.sessionStorage.setItem) { | ||
pushToSessionStorage(req); | ||
} | ||
}); | ||
return xhr; | ||
lastRequestBody = payload; | ||
originalSend.apply(xhr, arguments); | ||
}; | ||
xhr.setRequestHeader = function() { | ||
lastRequestHeader[arguments[0]] = arguments[1]; | ||
originalSetRequestHeader.apply(xhr, arguments); | ||
}; | ||
xhr.addEventListener('load', function() { | ||
var req = { | ||
url: lastURL, | ||
method: lastMethod.toUpperCase(), | ||
headers: xhr.getAllResponseHeaders(), | ||
requestHeaders: lastRequestHeader, | ||
// IE9 comp: need xhr.responseText | ||
body: xhr.response || xhr.responseText, | ||
statusCode: xhr.status, | ||
requestBody: lastRequestBody | ||
}; | ||
window[NAMESPACE].requests.push(req); | ||
if (window.sessionStorage && window.sessionStorage.setItem) { | ||
pushToSessionStorage(req); | ||
} | ||
}); | ||
return xhr; | ||
}; | ||
done(window[NAMESPACE]); | ||
done(window[NAMESPACE]); | ||
function pushToSessionStorage (req) { | ||
var rawData = window.sessionStorage.getItem(NAMESPACE); | ||
var parsed; | ||
if (rawData) { | ||
try { | ||
parsed = JSON.parse(rawData); | ||
} catch (e) { | ||
throw new Error('Could not parse sessionStorage data: ' + e.message); | ||
} | ||
} else { | ||
parsed = []; | ||
} | ||
parsed.push(req); | ||
window.sessionStorage.setItem(NAMESPACE, JSON.stringify(parsed)); | ||
function pushToSessionStorage(req) { | ||
var rawData = window.sessionStorage.getItem(NAMESPACE); | ||
var parsed; | ||
if (rawData) { | ||
try { | ||
parsed = JSON.parse(rawData); | ||
} catch (e) { | ||
throw new Error('Could not parse sessionStorage data: ' + e.message); | ||
} | ||
} else { | ||
parsed = []; | ||
} | ||
parsed.push(req); | ||
window.sessionStorage.setItem(NAMESPACE, JSON.stringify(parsed)); | ||
} | ||
function polyfillFormDataEntries() { | ||
var originalAppend = FormData.prototype.append; | ||
FormData.prototype.append = function() { | ||
this.__entries = this.__entries || []; | ||
this.__entries.push(Array.prototype.slice.call(arguments)); | ||
originalAppend.apply(this, arguments); | ||
}; | ||
FormData.prototype.entries = function() { | ||
return this.__entries; | ||
}; | ||
} | ||
}, | ||
getRequest: function getRequest (index) { | ||
function polyfillFormDataEntries() { | ||
var originalAppend = FormData.prototype.append; | ||
FormData.prototype.append = function() { | ||
this.__entries = this.__entries || []; | ||
this.__entries.push(Array.prototype.slice.call(arguments)); | ||
originalAppend.apply(this, arguments); | ||
}; | ||
FormData.prototype.entries = function() { | ||
return this.__entries; | ||
}; | ||
} | ||
}, | ||
getRequest: function getRequest(index) { | ||
var NAMESPACE = '__webdriverajax'; | ||
var NAMESPACE = '__webdriverajax'; | ||
var requests; | ||
var requests; | ||
if (window.sessionStorage && window.sessionStorage.getItem) { | ||
requests = getFromSessionStorage(); | ||
} else { | ||
requests = window[NAMESPACE].requests; | ||
} | ||
if (window.sessionStorage && window.sessionStorage.getItem) { | ||
requests = getFromSessionStorage(); | ||
} else { | ||
requests = window[NAMESPACE].requests; | ||
function getFromSessionStorage() { | ||
var rawData = window.sessionStorage.getItem(NAMESPACE); | ||
var parsed; | ||
if (rawData) { | ||
try { | ||
parsed = JSON.parse(rawData); | ||
} catch (e) { | ||
throw new Error('Could not parse sessionStorage data: ' + e.message); | ||
} | ||
} | ||
window.sessionStorage.removeItem(NAMESPACE); | ||
return parsed; | ||
} | ||
function getFromSessionStorage () { | ||
var rawData = window.sessionStorage.getItem(NAMESPACE); | ||
var parsed; | ||
if (rawData) { | ||
try { | ||
parsed = JSON.parse(rawData); | ||
} catch (e) { | ||
throw new Error('Could not parse sessionStorage data: ' + e.message); | ||
} | ||
} | ||
window.sessionStorage.removeItem(NAMESPACE); | ||
return parsed; | ||
} | ||
if (index == null) { | ||
return requests; | ||
} | ||
if (index == null) { | ||
return requests; | ||
} | ||
return requests[index]; | ||
} | ||
return requests[index]; | ||
} | ||
}; | ||
module.exports = interceptor; |
{ | ||
"name": "webdriverajax", | ||
"version": "2.2.0", | ||
"version": "3.0.0-beta.1", | ||
"description": "Capture and assert HTTP ajax calls in webdriver.io 🕸", | ||
"main": "index.js", | ||
"scripts": { | ||
"test": "eslint lib test index.js && wdio", | ||
"fix": "prettier --write --single-quote '{,!(node_modules)/**/}*.js'", | ||
"test": "wdio", | ||
"pretest": "selenium-standalone install" | ||
@@ -31,9 +32,16 @@ }, | ||
"devDependencies": { | ||
"eslint": "^4.13.1", | ||
"mocha": "^4.0.1", | ||
"husky": "^0.15.0-rc.9", | ||
"mocha": "^5.0.0", | ||
"node-static": "^0.7.10", | ||
"selenium-standalone": "^6.12.0", | ||
"prettier": "^1.11.1", | ||
"selenium-standalone": "^6.13.0", | ||
"wdio-mocha-framework": "^0.5.12", | ||
"webdriverio": "^4.9.11" | ||
}, | ||
"husky": { | ||
"hooks": { | ||
"pre-commit": "yarn fix", | ||
"pre-push": "yarn fix" | ||
} | ||
} | ||
} |
'use strict'; | ||
var assert = require('assert'); | ||
const assert = require('assert'); | ||
describe('webdriverajax', function () { | ||
describe('webdriverajax', function testSuite() { | ||
this.timeout(process.env.CI ? 100000 : 10000); | ||
this.timeout(process.env.CI ? 100000 : 10000); | ||
const wait = process.env.CI ? 10000 : 1000; | ||
var wait = process.env.CI ? 10000 : 1000; | ||
it('sets up the interceptor', function () { | ||
assert.equal(typeof browser.setupInterceptor, 'function'); | ||
browser.url('/get.html'); | ||
browser.setupInterceptor(); | ||
var ret = browser.execute(function checkSetup () { | ||
return window.__webdriverajax; | ||
}); | ||
assert.deepEqual(ret.value, { requests: [] }); | ||
it('sets up the interceptor', () => { | ||
assert.equal(typeof browser.setupInterceptor, 'function'); | ||
browser.url('/get.html'); | ||
browser.setupInterceptor(); | ||
const ret = browser.execute(() => { | ||
return window.__webdriverajax; | ||
}); | ||
assert.deepEqual(ret.value, { requests: [] }); | ||
}); | ||
it('can intercept a simple GET request', function () { | ||
browser.url('/get.html').setupInterceptor(); | ||
browser.expectRequest('GET', '/get.json', 200); | ||
browser.click('#button').pause(wait); | ||
browser.assertRequests(); | ||
}); | ||
it('can intercept a simple GET request', () => { | ||
browser.url('/get.html').setupInterceptor(); | ||
browser.expectRequest('GET', '/get.json', 200); | ||
browser.click('#button').pause(wait); | ||
browser.assertRequests(); | ||
}); | ||
it('can use regular expressions for urls', function () { | ||
browser.url('/get.html').setupInterceptor(); | ||
browser.expectRequest('GET', /get\.json/, 200); | ||
browser.click('#button').pause(wait); | ||
browser.assertRequests(); | ||
}); | ||
it('can use regular expressions for urls', () => { | ||
browser.url('/get.html').setupInterceptor(); | ||
browser.expectRequest('GET', /get\.json/, 200); | ||
browser.click('#button').pause(wait); | ||
browser.assertRequests(); | ||
}); | ||
it('errors on wrong request count', function () { | ||
browser.url('/get.html').setupInterceptor(); | ||
browser | ||
.expectRequest('GET', '/get.json', 200) | ||
.expectRequest('GET', '/get.json', 200); | ||
browser.click('#button').pause(wait); | ||
assert.throws(function () { | ||
browser.assertRequests(); | ||
}, /Expected/); | ||
}); | ||
it('errors on wrong request count', () => { | ||
browser.url('/get.html').setupInterceptor(); | ||
browser | ||
.expectRequest('GET', '/get.json', 200) | ||
.expectRequest('GET', '/get.json', 200); | ||
browser.click('#button').pause(wait); | ||
assert.throws(() => { | ||
browser.assertRequests(); | ||
}, /Expected/); | ||
}); | ||
it('errors on wrong method', function () { | ||
browser.url('/get.html').setupInterceptor(); | ||
browser.expectRequest('PUT', '/get.json', 200); | ||
browser.click('#button').pause(wait); | ||
assert.throws(function () { | ||
browser.assertRequests(); | ||
}, /PUT/); | ||
}); | ||
it('errors on wrong method', () => { | ||
browser.url('/get.html').setupInterceptor(); | ||
browser.expectRequest('PUT', '/get.json', 200); | ||
browser.click('#button').pause(wait); | ||
assert.throws(() => { | ||
browser.assertRequests(); | ||
}, /PUT/); | ||
}); | ||
it('errors on wrong URL', function () { | ||
browser.url('/get.html').setupInterceptor(); | ||
browser.expectRequest('GET', '/wrong.json', 200); | ||
browser.click('#button').pause(wait); | ||
assert.throws(function () { | ||
browser.assertRequests(); | ||
}, /wrong\.json/); | ||
}); | ||
it('errors on wrong URL', () => { | ||
browser.url('/get.html').setupInterceptor(); | ||
browser.expectRequest('GET', '/wrong.json', 200); | ||
browser.click('#button').pause(wait); | ||
assert.throws(() => { | ||
browser.assertRequests(); | ||
}, /wrong\.json/); | ||
}); | ||
it('errors if regex doesn\'t match URL', function () { | ||
browser.url('/get.html').setupInterceptor(); | ||
browser.expectRequest('GET', /wrong\.json/, 200); | ||
browser.click('#button').pause(wait); | ||
assert.throws(function () { | ||
browser.assertRequests(); | ||
}, /get\.json/); | ||
it("errors if regex doesn't match URL", () => { | ||
browser.url('/get.html').setupInterceptor(); | ||
browser.expectRequest('GET', /wrong\.json/, 200); | ||
browser.click('#button').pause(wait); | ||
assert.throws(() => { | ||
browser.assertRequests(); | ||
}, /get\.json/); | ||
}); | ||
}); | ||
it('errors on wrong status code', () => { | ||
browser.url('/get.html').setupInterceptor(); | ||
browser.expectRequest('GET', '/get.json', 404); | ||
browser.click('#button').pause(wait); | ||
assert.throws(() => { | ||
browser.assertRequests(); | ||
}, /404/); | ||
}); | ||
it('errors on wrong status code', function () { | ||
browser.url('/get.html').setupInterceptor(); | ||
browser.expectRequest('GET', '/get.json', 404); | ||
browser.click('#button').pause(wait); | ||
assert.throws(function () { | ||
browser.assertRequests(); | ||
}, /404/); | ||
}); | ||
it('can access a certain request', () => { | ||
browser.url('/get.html').setupInterceptor(); | ||
browser.click('#button').pause(wait); | ||
const request = browser.getRequest(0); | ||
assert.equal(request.method, 'GET'); | ||
assert.equal(request.url, '/get.json'); | ||
assert.deepEqual(request.response.body, { OK: true }); | ||
assert.equal(request.response.statusCode, 200); | ||
assert.equal(request.response.headers['content-length'], '15'); | ||
}); | ||
it('can access a certain request', function () { | ||
browser.url('/get.html').setupInterceptor(); | ||
browser.click('#button').pause(wait); | ||
var request = browser.getRequest(0); | ||
assert.equal(request.method, 'GET'); | ||
assert.equal(request.url, '/get.json'); | ||
assert.deepEqual(request.response.body, { OK: true }); | ||
assert.equal(request.response.statusCode, 200); | ||
assert.equal(request.response.headers['content-length'], '15'); | ||
}); | ||
it('can get multiple requests', () => { | ||
browser.url('/get.html').setupInterceptor(); | ||
browser.click('#button').pause(wait); | ||
browser.click('#button').pause(wait); | ||
const requests = browser.getRequests(); | ||
assert(Array.isArray(requests)); | ||
assert.equal(requests.length, 2); | ||
assert.equal(requests[0].method, 'GET'); | ||
assert.equal(requests[1].method, 'GET'); | ||
}); | ||
it('can get multiple requests', function () { | ||
browser.url('/get.html').setupInterceptor(); | ||
browser.click('#button').pause(wait); | ||
browser.click('#button').pause(wait); | ||
var requests = browser.getRequests(); | ||
assert(Array.isArray(requests)); | ||
assert.equal(requests.length, 2); | ||
assert.equal(requests[0].method, 'GET'); | ||
assert.equal(requests[1].method, 'GET'); | ||
}); | ||
it('survives page changes', () => { | ||
browser.url('/page_change.html').setupInterceptor(); | ||
browser.click('#button1').pause(wait); | ||
const requests = browser.getRequests(); | ||
assert(Array.isArray(requests)); | ||
assert.equal(requests.length, 1); | ||
assert.equal(requests[0].method, 'GET'); | ||
}); | ||
it('survives page changes', function () { | ||
browser.url('/page_change.html').setupInterceptor(); | ||
browser.click('#button1').pause(wait); | ||
var requests = browser.getRequests(); | ||
assert(Array.isArray(requests)); | ||
assert.equal(requests.length, 1); | ||
assert.equal(requests[0].method, 'GET'); | ||
}); | ||
it('survives page changes using multiple requests', () => { | ||
browser.url('/page_change.html').setupInterceptor(); | ||
browser | ||
.click('#button1') | ||
.click('#button2') | ||
.pause(wait); | ||
const requests = browser.getRequests(); | ||
assert(Array.isArray(requests)); | ||
assert.equal(requests.length, 2); | ||
assert.equal(requests[0].method, 'GET'); | ||
assert.equal(requests[1].method, 'GET'); | ||
}); | ||
it('survives page changes using multiple requests', function () { | ||
browser.url('/page_change.html').setupInterceptor(); | ||
browser.click('#button1').click('#button2').pause(wait); | ||
var requests = browser.getRequests(); | ||
assert(Array.isArray(requests)); | ||
assert.equal(requests.length, 2); | ||
assert.equal(requests[0].method, 'GET'); | ||
assert.equal(requests[1].method, 'GET'); | ||
}); | ||
it('can assess the request body using string data', () => { | ||
browser.url('/post.html').setupInterceptor(); | ||
browser.click('#buttonstring').pause(wait); | ||
const request = browser.getRequest(0); | ||
assert.equal(request.body, 'foobar'); | ||
}); | ||
it('can assess the request body using string data', function () { | ||
browser.url('/post.html').setupInterceptor(); | ||
browser.click('#buttonstring').pause(wait); | ||
var request = browser.getRequest(0); | ||
assert.equal(request.body, 'foobar'); | ||
}); | ||
it('can assess the request body using JSON data', () => { | ||
browser.url('/post.html').setupInterceptor(); | ||
browser.click('#buttonjson').pause(wait); | ||
const request = browser.getRequest(0); | ||
assert.deepEqual(request.body, { foo: 'bar' }); | ||
}); | ||
it('can assess the request body using JSON data', function () { | ||
browser.url('/post.html').setupInterceptor(); | ||
browser.click('#buttonjson').pause(wait); | ||
var request = browser.getRequest(0); | ||
assert.deepEqual(request.body, { foo: 'bar' }); | ||
}); | ||
it('can assess the request body using form data', () => { | ||
browser.url('/post.html').setupInterceptor(); | ||
browser.click('#buttonform').pause(wait); | ||
const request = browser.getRequest(0); | ||
assert.deepEqual(request.body, { foo: ['bar'] }); | ||
}); | ||
it('can assess the request body using form data', function () { | ||
browser.url('/post.html').setupInterceptor(); | ||
browser.click('#buttonform').pause(wait); | ||
var request = browser.getRequest(0); | ||
assert.deepEqual(request.body, { foo: ['bar'] }); | ||
}); | ||
it('can assess the request body using JSON data', () => { | ||
browser.url('/post.html').setupInterceptor(); | ||
browser.click('#buttonjson').pause(wait); | ||
const request = browser.getRequest(0); | ||
assert.equal(request.headers['content-type'], 'application/json'); | ||
}); | ||
it('can assess the request body using JSON data', function () { | ||
browser.url('/post.html').setupInterceptor(); | ||
browser.click('#buttonjson').pause(wait); | ||
var request = browser.getRequest(0); | ||
assert.equal(request.headers['content-type'], 'application/json'); | ||
it('can get initialised inside an iframe', () => { | ||
browser.url('/frame.html').setupInterceptor(); | ||
const ret = browser.execute(function checkSetup() { | ||
return window.__webdriverajax; | ||
}); | ||
it('can get initialised inside an iframe', function () { | ||
browser.url('/frame.html').setupInterceptor(); | ||
var ret = browser.execute(function checkSetup () { | ||
return window.__webdriverajax; | ||
}); | ||
assert.deepEqual(ret.value, { requests: [] }); | ||
browser.waitForExist('#getinframe'); | ||
var frame = browser.element('#getinframe'); | ||
browser.frame(frame.value); | ||
browser.setupInterceptor(); | ||
var frameRet = browser.execute(function checkSetup () { | ||
return window.__webdriverajax; | ||
}); | ||
assert.deepEqual(frameRet.value, { requests: [] }); | ||
browser.expectRequest('GET', '/get.json', 200); | ||
browser.click('#button').pause(wait); | ||
browser.assertRequests(); | ||
browser.frameParent(); | ||
assert.throws(() => { | ||
browser.assertRequests(); | ||
}); | ||
assert.deepEqual(ret.value, { requests: [] }); | ||
browser.waitForExist('#getinframe'); | ||
const frame = browser.element('#getinframe'); | ||
browser.frame(frame.value); | ||
browser.setupInterceptor(); | ||
const frameRet = browser.execute(function checkSetup() { | ||
return window.__webdriverajax; | ||
}); | ||
it('errors with no requests set up', function () { | ||
browser.url('/get.html').setupInterceptor(); | ||
assert.throws(() => { | ||
browser.assertRequests(); | ||
}, /No\sexpectations\sfound/); | ||
assert.deepEqual(frameRet.value, { requests: [] }); | ||
browser.expectRequest('GET', '/get.json', 200); | ||
browser.click('#button').pause(wait); | ||
browser.assertRequests(); | ||
browser.frameParent(); | ||
assert.throws(() => { | ||
browser.assertRequests(); | ||
}); | ||
}); | ||
it('errors properly when no requests were captured', function () { | ||
browser.url('/get.html').setupInterceptor(); | ||
browser.expectRequest('GET', '/get.json', 200); | ||
assert.throws(() => { | ||
browser.assertRequests(); | ||
}, /No\srequests\scaptured/); | ||
}); | ||
it('errors with no requests set up', () => { | ||
browser.url('/get.html').setupInterceptor(); | ||
assert.throws(() => { | ||
browser.assertRequests(); | ||
}, /No\sexpectations\sfound/); | ||
}); | ||
it('returns an empty array for no captured requests', () => { | ||
browser.url('/get.html').setupInterceptor(); | ||
const count = browser.getRequests(); | ||
assert.deepEqual(count, []); | ||
}); | ||
}); |
'use strict'; | ||
var http = require('http'); | ||
const http = require('http'); | ||
var selenium = require('selenium-standalone'); | ||
var nodeStatic = require('node-static'); | ||
const selenium = require('selenium-standalone'); | ||
const nodeStatic = require('node-static'); | ||
var grid, staticServer; | ||
let grid, staticServer; | ||
module.exports = { | ||
startStaticServer, | ||
stopStaticServer, | ||
startSelenium, | ||
stopSelenium | ||
startStaticServer, | ||
stopStaticServer, | ||
startSelenium, | ||
stopSelenium | ||
}; | ||
function startStaticServer () { | ||
return new Promise(function (resolve, reject) { | ||
var file = new nodeStatic.Server('./test/site'); | ||
var server = http.createServer(function (request, response) { | ||
request.addListener('end', function () { | ||
file.serve(request, response); | ||
}).resume(); | ||
}).listen(8080, function (err) { | ||
if (err) { | ||
return reject(err); | ||
} | ||
console.log('Started static server on port ' + 8080); | ||
staticServer = server; | ||
resolve(server); | ||
}); | ||
}); | ||
function startStaticServer() { | ||
return new Promise((resolve, reject) => { | ||
const file = new nodeStatic.Server('./test/site'); | ||
const server = http | ||
.createServer((request, response) => { | ||
request | ||
.addListener('end', () => { | ||
file.serve(request, response); | ||
}) | ||
.resume(); | ||
}) | ||
.listen(8080, err => { | ||
if (err) { | ||
return reject(err); | ||
} | ||
console.log('Started static server on port ' + 8080); | ||
staticServer = server; | ||
resolve(server); | ||
}); | ||
}); | ||
} | ||
function startSelenium () { | ||
return new Promise(function (resolve, reject) { | ||
selenium.start(function (err, sel) { | ||
if (err) { | ||
return reject(err); | ||
} | ||
console.log('Started Selenium server'); | ||
grid = sel; | ||
resolve(sel); | ||
}); | ||
function startSelenium() { | ||
return new Promise((resolve, reject) => { | ||
selenium.start((err, sel) => { | ||
if (err) { | ||
return reject(err); | ||
} | ||
console.log('Started Selenium server'); | ||
grid = sel; | ||
resolve(sel); | ||
}); | ||
}); | ||
} | ||
function stopSelenium () { | ||
return new Promise(function (resolve, reject) { | ||
grid.on('exit', function () { | ||
resolve(true); | ||
}); | ||
grid.kill(); | ||
function stopSelenium() { | ||
return new Promise((resolve, reject) => { | ||
grid.on('exit', () => { | ||
resolve(true); | ||
}); | ||
grid.kill(); | ||
}); | ||
} | ||
function stopStaticServer () { | ||
return new Promise(function (resolve, reject) { | ||
staticServer.close(function onClose () { | ||
resolve(true); | ||
}); | ||
function stopStaticServer() { | ||
return new Promise((resolve, reject) => { | ||
staticServer.close(() => { | ||
resolve(true); | ||
}); | ||
}); | ||
} |
250
wdio.conf.js
'use strict'; | ||
var path = require('path'); | ||
const path = require('path'); | ||
var utils = require('./test/utils'); | ||
const utils = require('./test/utils'); | ||
var plugin = path.resolve(__dirname, 'index.js'); | ||
const plugin = path.resolve(__dirname, 'index.js'); | ||
var config = { | ||
const config = { | ||
// | ||
// ================== | ||
// Specify Test Files | ||
// ================== | ||
// Define which test specs should run. The pattern is relative to the directory | ||
// from which `wdio` was called. Notice that, if you are calling `wdio` from an | ||
// NPM script (see https://docs.npmjs.com/cli/run-script) then the current working | ||
// directory is where your package.json resides, so `wdio` will be called from there. | ||
// | ||
specs: ['./test/spec/plugin_test.js'], | ||
// Patterns to exclude. | ||
exclude: [ | ||
// 'path/to/excluded/files' | ||
], | ||
// | ||
// ============ | ||
// Capabilities | ||
// ============ | ||
// Define your capabilities here. WebdriverIO can run multiple capabilties at the same | ||
// time. Depending on the number of capabilities, WebdriverIO launches several test | ||
// sessions. Within your capabilities you can overwrite the spec and exclude option in | ||
// order to group specific specs to a specific capability. | ||
// | ||
// If you have trouble getting all important capabilities together, check out the | ||
// Sauce Labs platform configurator - a great tool to configure your capabilities: | ||
// https://docs.saucelabs.com/reference/platforms-configurator | ||
// | ||
capabilities: [ | ||
{ | ||
browserName: 'chrome', | ||
chromeOptions: { | ||
args: ['headless', 'no-sandbox'] | ||
} | ||
} | ||
], | ||
// | ||
// =================== | ||
// Test Configurations | ||
// =================== | ||
// Define all options that are relevant for the WebdriverIO instance here | ||
// | ||
// Level of logging verbosity. | ||
logLevel: 'silent', | ||
// | ||
// Enables colors for log output. | ||
coloredLogs: true, | ||
// | ||
// Saves a screenshot to a given path if a command fails. | ||
screenshotPath: './errorShots/', | ||
// | ||
// Set a base URL in order to shorten url command calls. If your url parameter starts | ||
// with "/", the base url gets prepended. | ||
baseUrl: 'http://localhost:8080', | ||
// | ||
// Default timeout for all waitForXXX commands. | ||
waitforTimeout: 10000, | ||
// | ||
// Initialize the browser instance with a WebdriverIO plugin. The object should have the | ||
// plugin name as key and the desired plugin options as property. Make sure you have | ||
// the plugin installed before running any tests. The following plugins are currently | ||
// available: | ||
// WebdriverCSS: https://github.com/webdriverio/webdrivercss | ||
// WebdriverRTC: https://github.com/webdriverio/webdriverrtc | ||
// Browserevent: https://github.com/webdriverio/browserevent | ||
plugins: {}, | ||
// | ||
// Framework you want to run your specs with. | ||
// The following are supported: mocha, jasmine and cucumber | ||
// see also: http://webdriver.io/guide/testrunner/frameworks.html | ||
// | ||
// Make sure you have the node package for the specific framework installed before running | ||
// any tests. If not please install the following package: | ||
// Mocha: `$ npm install mocha` | ||
// Jasmine: `$ npm install jasmine` | ||
// Cucumber: `$ npm install cucumber` | ||
framework: 'mocha', | ||
// | ||
// Test reporter for stdout. | ||
// The following are supported: dot (default), spec and xunit | ||
// see also: http://webdriver.io/guide/testrunner/reporters.html | ||
reporter: 'spec', | ||
// | ||
// ================== | ||
// Specify Test Files | ||
// ================== | ||
// Define which test specs should run. The pattern is relative to the directory | ||
// from which `wdio` was called. Notice that, if you are calling `wdio` from an | ||
// NPM script (see https://docs.npmjs.com/cli/run-script) then the current working | ||
// directory is where your package.json resides, so `wdio` will be called from there. | ||
// | ||
specs: [ | ||
'./test/spec/plugin_test.js' | ||
], | ||
// Patterns to exclude. | ||
exclude: [ | ||
// 'path/to/excluded/files' | ||
], | ||
// | ||
// ============ | ||
// Capabilities | ||
// ============ | ||
// Define your capabilities here. WebdriverIO can run multiple capabilties at the same | ||
// time. Depending on the number of capabilities, WebdriverIO launches several test | ||
// sessions. Within your capabilities you can overwrite the spec and exclude option in | ||
// order to group specific specs to a specific capability. | ||
// | ||
// If you have trouble getting all important capabilities together, check out the | ||
// Sauce Labs platform configurator - a great tool to configure your capabilities: | ||
// https://docs.saucelabs.com/reference/platforms-configurator | ||
// | ||
capabilities: [{ | ||
browserName: 'chrome', | ||
chromeOptions: { | ||
args: ['headless', 'no-sandbox'] | ||
} | ||
}], | ||
// | ||
// =================== | ||
// Test Configurations | ||
// =================== | ||
// Define all options that are relevant for the WebdriverIO instance here | ||
// | ||
// Level of logging verbosity. | ||
logLevel: 'silent', | ||
// | ||
// Enables colors for log output. | ||
coloredLogs: true, | ||
// | ||
// Saves a screenshot to a given path if a command fails. | ||
screenshotPath: './errorShots/', | ||
// | ||
// Set a base URL in order to shorten url command calls. If your url parameter starts | ||
// with "/", the base url gets prepended. | ||
baseUrl: 'http://localhost:8080', | ||
// | ||
// Default timeout for all waitForXXX commands. | ||
waitforTimeout: 10000, | ||
// | ||
// Initialize the browser instance with a WebdriverIO plugin. The object should have the | ||
// plugin name as key and the desired plugin options as property. Make sure you have | ||
// the plugin installed before running any tests. The following plugins are currently | ||
// available: | ||
// WebdriverCSS: https://github.com/webdriverio/webdrivercss | ||
// WebdriverRTC: https://github.com/webdriverio/webdriverrtc | ||
// Browserevent: https://github.com/webdriverio/browserevent | ||
plugins: { | ||
}, | ||
// | ||
// Framework you want to run your specs with. | ||
// The following are supported: mocha, jasmine and cucumber | ||
// see also: http://webdriver.io/guide/testrunner/frameworks.html | ||
// | ||
// Make sure you have the node package for the specific framework installed before running | ||
// any tests. If not please install the following package: | ||
// Mocha: `$ npm install mocha` | ||
// Jasmine: `$ npm install jasmine` | ||
// Cucumber: `$ npm install cucumber` | ||
framework: 'mocha', | ||
// | ||
// Test reporter for stdout. | ||
// The following are supported: dot (default), spec and xunit | ||
// see also: http://webdriver.io/guide/testrunner/reporters.html | ||
reporter: 'spec', | ||
// | ||
// Options to be passed to Mocha. | ||
// See the full list at http://mochajs.org/ | ||
mochaOpts: { | ||
ui: 'bdd' | ||
}, | ||
// | ||
// Options to be passed to Mocha. | ||
// See the full list at http://mochajs.org/ | ||
mochaOpts: { | ||
ui: 'bdd' | ||
}, | ||
// | ||
// ===== | ||
// Hooks | ||
// ===== | ||
// Run functions before or after the test. If one of them returns with a promise, WebdriverIO | ||
// will wait until that promise got resolved to continue. | ||
// see also: http://webdriver.io/guide/testrunner/hooks.html | ||
// | ||
// Gets executed before all workers get launched. | ||
onPrepare: function() { | ||
var jobs = [ | ||
utils.startStaticServer(), | ||
utils.startSelenium() | ||
]; | ||
return Promise.all(jobs); | ||
}, | ||
// | ||
// Gets executed before test execution begins. At this point you will have access to all global | ||
// variables like `browser`. It is the perfect place to define custom commands. | ||
before: function() { | ||
// do something | ||
}, | ||
// | ||
// Gets executed after all tests are done. You still have access to all global variables from | ||
// the test. | ||
after: function(failures, pid) {}, | ||
// | ||
// Gets executed after all workers got shut down and the process is about to exit. It is not | ||
// possible to defer the end of the process using a promise. | ||
onComplete: function() { | ||
var jobs = [ | ||
utils.stopStaticServer(), | ||
utils.stopSelenium(), | ||
]; | ||
return Promise.all(jobs); | ||
} | ||
// | ||
// ===== | ||
// Hooks | ||
// ===== | ||
// Run functions before or after the test. If one of them returns with a promise, WebdriverIO | ||
// will wait until that promise got resolved to continue. | ||
// see also: http://webdriver.io/guide/testrunner/hooks.html | ||
// | ||
// Gets executed before all workers get launched. | ||
onPrepare() { | ||
const jobs = [utils.startStaticServer(), utils.startSelenium()]; | ||
return Promise.all(jobs); | ||
}, | ||
// | ||
// Gets executed before test execution begins. At this point you will have access to all global | ||
// variables like `browser`. It is the perfect place to define custom commands. | ||
before() { | ||
// do something | ||
}, | ||
// | ||
// Gets executed after all tests are done. You still have access to all global variables from | ||
// the test. | ||
after(failures, pid) {}, | ||
// | ||
// Gets executed after all workers got shut down and the process is about to exit. It is not | ||
// possible to defer the end of the process using a promise. | ||
onComplete() { | ||
const jobs = [utils.stopStaticServer(), utils.stopSelenium()]; | ||
return Promise.all(jobs); | ||
} | ||
}; | ||
@@ -138,0 +130,0 @@ |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
153600
662
7
1