Intercept in webdriverIO do not catch api request - testing

Trying to apply Intercept in the webdriverIO test use WDIO CLI (testrunner)
describe('Main flow for order', () => {
if (browser.isChrome) {
it('should login with valid credentials', async () => {
await browser.url(`/`);
await browser.setupInterceptor()
await browser.expectRequest('GET', 'https://master.k.sollerstr.ru/api/orders/summary', 200);
await $('input[type="text"]').setValue('user#****.com');
await $('input[type="password"]').setValue('****');
await $('.el-button_primary').click();
// await browser.assertRequests();
await browser.assertExpectedRequestsOnly();
});
}
})
I know that this request is processed after clicking the button,because I have written a similar test in Cypress and it catches this api but i have error after run the test in my webdriverIO project:
What am I doing wrong. Use webdriverIO Intercept Service.
2021-12-13T19:54:53.126Z INFO webdriver: COMMAND elementClick("f4a2ea9c-737b-4893-bffa-3263d5d2cf22")
[1-0] 2021-12-13T19:54:53.126Z INFO webdriver: [POST] http://localhost:4444/session/c96a4af66042283314f35b1ed3e00746/element/f4a2ea9c-737b-4893-bffa-3263d5d2cf22/click
[1-0] 2021-12-13T19:54:53.162Z INFO webdriver: COMMAND assertExpectedRequestsOnly()
[1-0] 2021-12-13T19:54:53.162Z INFO webdriver: COMMAND executeScript(<fn>, <object>)
[1-0] 2021-12-13T19:54:53.162Z INFO webdriver: [POST] http://localhost:4444/session/c96a4af66042283314f35b1ed3e00746/execute/sync
[1-0] 2021-12-13T19:54:53.163Z INFO webdriver: DATA {
[1-0] script: 'return (function getRequest(index, options) {\n' +
[1-0] " var NAMESPACE = '__webdriverajax';\n" +
[1-0] " var PKG_PREFIX = '[wdio-intercept-service]: ';\n" +
[1-0] '\n' +
[1-0] ' function getFromSessionStorage() {\n' +
[1-0] ' var rawData = window.sessionStorage.getItem(NAMESPACE);\n' +
[1-0] ' var parsed;\n' +
[1-0] ' if (rawData) {\n' +
[1-0] ' try {\n' +
[1-0] ' parsed = JSON.parse(rawData);\n' +
[1-0] ' } catch (e) {\n' +
[1-0] ' throw new Error(\n' +
[1-0] " PKG_PREFIX + 'Could not parse sessionStorage data: ' + e.message\n" +
[1-0] ' );\n' +
[1-0] ' }\n' +
[1-0] ' }\n' +
[1-0] ' return parsed;\n' +
[1-0] ' }\n' +
[1-0] ' function getAllRequests() {\n' +
[1-0] ' // Session storage will always return an array that can be mutated freely.\n' +
[1-0] ' if (window.sessionStorage && window.sessionStorage.getItem) {\n' +
[1-0] ' return getFromSessionStorage() || [];\n' +
[1-0] ' }\n' +
[1-0] ' // But if we have to use the active namespace array, then return a copy of it.\n' +
[1-0] ' var shouldClone = window[NAMESPACE].requests;\n' +
[1-0] ' return shouldClone ? shouldClone.slice() : [];\n' +
[1-0] ' }\n' +
[1-0] ' function isComplete(r) {\n' +
[1-0] " return typeof r.__fulfilled === 'number';\n" +
[1-0] ' }\n' +
[1-0] '\n' +
[1-0] ' var requests = getAllRequests();\n' +
[1-0] '\n' +
[1-0] " var shouldSortByEnd = String(options.orderBy).toUpperCase() !== 'START';\n" +
[1-0] ' if (shouldSortByEnd) {\n' +
[1-0] ' // Sort ascending by time of fulfillment. If not fulfilled yet, sort to the end!\n' +
[1-0] ' requests.sort(function (a, b) {\n' +
[1-0] ' var hasA = isComplete(a);\n' +
[1-0] ' var hasB = isComplete(b);\n' +
[1-0] ' if (hasA && hasB) return a.__fulfilled - b.__fulfilled;\n' +
[1-0] ' if (hasA) return -1; // Only A is fulfilled, so order A before B\n' +
[1-0] ' if (hasB) return 1; // Only B is fulfilled, so order A after B\n' +
[1-0] ' return 0; // Preserve ordering of A & B.\n' +
[1-0] ' });\n' +
[1-0] ' }\n' +
[1-0] '\n' +
[1-0] ' var includePending = Boolean(options.includePending);\n' +
[1-0] ' if (index == null) {\n' +
[1-0] ' return includePending ? requests : requests.filter(isComplete);\n' +
[1-0] ' }\n' +
[1-0] '\n' +
[1-0] ' if (!includePending) {\n' +
[1-0] ' // Filter out the pending requests and index only into the completed requests.\n' +
[1-0] ' return requests.filter(isComplete)[index];\n' +
[1-0] ' }\n' +
[1-0] ' return requests[index];\n' +
[1-0] ' }).apply(null, arguments)',
[1-0] args: [ undefined, {} ]
[1-0] }
[1-0] 2021-12-13T19:54:53.169Z INFO webdriver: RESULT []
[1-0] Error in "Main flow for order.should login with valid credentials"
Error: Expected request was not found. method: GET url: https://master.k.sollerstr.ru/api/orders/summary statusCode: 200
at /home/pavel/WebstormProjects/new_design/node_modules/wdio-intercept-service/index.js:213:15
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async Browser.wrapCommandFn (/home/pavel/WebstormProjects/new_design/node_modules/#wdio/utils/build/shim.js:131:29)
[1-0] 2021-12-13T19:54:53.170Z INFO webdriver: COMMAND deleteSession()
[1-0] 2021-12-13T19:54:53.170Z INFO webdriver: [DELETE] http://localhost:4444/session/c96a4af66042283314f35b1ed3e00746
[1-0] FAILED in chrome - /test/testwd2.js

Related

SAP API Journal Entry "Post Journal Entries from External Systems" (SAP_COM_0002)

Has anyone successfully created a Journal Entry in S/4HANA Cloud system via POSTMAN or Cloud Platform App?
I keep getting 401 unauthorized in POSTMAN. I tried PO GET API URL, and it is working fine.
https://:/sap/bc/srt/scs/sap/journalentrycreaterequestconfi
{
"JournalEntryBulkCreateRequest": {
"MessageHeader": { "CreationDateTime": "2018-05-27T12:50:30.45+01:00" },
"JournalEntryCreateRequest": {
"MessageHeader": { "CreationDateTime": "2018-05-27T12:50:30.45+01:00" },
"JournalEntry": {
"OriginalReferenceDocumentLogicalSystem": "",
"OriginalReferenceDocumentType": "BKPFF",
"OriginalReferenceDocument": "",
"BusinessTransactionType": "RFBU",
"AccountingDocumentType": "",
"DocumentHeaderText": "Header Value",
"CompanyCode": "US01",
"CreatedByUser": "CB9980000010",
"DocumentDate": "2018-05-27",
"PostingDate": "2018-05-27",
"item": [
{
"GLAccount": "0021517000",
"AmountInTransactionCurrency": {
"Amount": "1200.00",
"currencyCode": "USD"
},
"DocumentItemText": "Text1"
},
{
"GLAccount": "0010010000",
"AmountInTransactionCurrency": {
"Amount": "-1200.00",
"currencyCode": "USD"
},
"DocumentItemText": "Text2"
}
]
}
}
}
This is a Soap Request so you need to call by sending XML Envelop data.
var request =
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope\"" +
" xmlns:sfin=\"http://sap.com/xi/SAPSCORE/SFIN\"><soapenv:Header/><soapenv:Body><sfin:JournalEntryBulkCreateRequest>" +
"<MessageHeader><CreationDateTime>" + currentDate.toISOString() + "</CreationDateTime></MessageHeader>" +
"<JournalEntryCreateRequest><MessageHeader><CreationDateTime>" + currentDate.toISOString() + "</CreationDateTime></MessageHeader>" +
"<JournalEntry>" +
"<OriginalReferenceDocumentType>BKPFF</OriginalReferenceDocumentType>" +
"<OriginalReferenceDocument>" + Item[1] + "</OriginalReferenceDocument>" + // Report number
"<OriginalReferenceDocumentLogicalSystem>INBOUND</OriginalReferenceDocumentLogicalSystem>" +
"<BusinessTransactionType>RFBU</BusinessTransactionType>" +
"<AccountingDocumentType>SA</AccountingDocumentType>" +
"<DocumentHeaderText>Certify NonReimbursement</DocumentHeaderText>" +
"<CreatedByUser>CC0000000001</CreatedByUser>" +
"<CompanyCode>" + Item[8] + "</CompanyCode>" +
"<DocumentDate>" + this.parseJsonDate(documentDate) + "</DocumentDate>" +
"<PostingDate>" + this.parseJsonDate(postingdate) + "</PostingDate>" +
"<Item>" +
"<CompanyCode>" + Item[8] + "</CompanyCode>" +
"<GLAccount>" + this.suffixZeros(nonExpAcc + "") + "</GLAccount>" +
"<AmountInTransactionCurrency currencyCode=\"" + Item[5] + "\">-" + Item[4] + "</AmountInTransactionCurrency>" +
"<DebitCreditCode>S</DebitCreditCode>" +
"</Item>" +
"<Item>" +
"<CompanyCode>" + Item[8] + "</CompanyCode>" +
"<GLAccount>" + this.suffixZeros(Item[3] + "") + "</GLAccount>" +
"<AmountInTransactionCurrency currencyCode=\"" + Item[5] + "\">" + Item[4] + "</AmountInTransactionCurrency>" +
"<DebitCreditCode>H</DebitCreditCode>" +
"<AccountAssignment>" +
"<CostCenter>" + this.suffixZeros(Item[7] + "") + "</CostCenter>" +
"</AccountAssignment>" +
"</Item>" +
"</JournalEntry></JournalEntryCreateRequest></sfin:JournalEntryBulkCreateRequest></soapenv:Body></soapenv:Envelope>";

Titanium Alloy - 'Global' Listener

I have multiple windows that 'require' livebar so that the entire bar persists over all windows. However, whenever the 'change' function is called, it works and logs, however my $.livebar_datalbl.text fails with the following error: "undefined is not an object (evaluating '$.livebar_datalbl.text = 'State: ' + e.description + ' (' + e.state + ')'')"
Am I structuring the code incorrectly or missing something?
index.js
(function constructor() {
audioPlayer = Ti.Media.createAudioPlayer({
url: 'https://allthingsaudio.wikispaces.com/file/view/Shuffle%20for%20K.M.mp3/139190697/Shuffle%20for%20K.M.mp3',
allowBackground: true
});
audioPlayer.addEventListener('progress', function(e) {
Ti.API.info('Time Played: ' + Math.round(e.progress) + ' milliseconds');
});
audioPlayer.addEventListener('change', function(e) {
$.livebar_datalbl.text = 'State: ' + e.description + ' (' + e.state + ')';
Ti.API.info('State: ' + e.description + ' (' + e.state + ')');
});
window = Alloy.createController('listen').getView();
window.open();
})();
livebar.xml
<Alloy>
<View class="livebar">
<View class="livebar_livelblcontainer">
<Label class="livebar_livelbl">LIVE</Label>
</View>
<Label class="livebar_datalbl" id="livebar_datalbl">HELLO WORLD</Label>
<ImageView id="livebar_playpausebtn" class="livebar_playpausebtn"/>
</View>
</Alloy>
livebar.js
$.livebar_playpausebtn.addEventListener('click', function(event) {
if (audioPlayer.playing || audioPlayer.paused) {
audioPlayer.stop();
if (Ti.Platform.name === 'android')
{
audioPlayer.release();
}
} else {
audioPlayer.start();
}
});
audioPlayer.addEventListener('progress', function(e) {
Ti.API.info('Time Played: ' + Math.round(e.progress) + ' milliseconds');
});
audioPlayer.addEventListener('change', function(e) {
$.livebar_datalbl.text = 'State: ' + e.description + ' (' + e.state + ')';
Ti.API.info('State: ' + e.description + ' (' + e.state + ')');
});
The audioPlayer.addEventListener event will only listen to events in the controller that you have created the audioPlayer in, in this case index.js. In your example the audioPlayer.addEventListener events in livebar.js have no effect as there is no audioPlayer to add event to.
If you would like to have the audioplayer in index.js and then have the livebar be updated and still keep the livebar in its own view+controller you will need to fire events across the controllers. To do this you can make use of Ti.App.fireEvent
You can read more here - Search for the "Application-Level Events" Section
http://docs.appcelerator.com/platform/latest/#!/guide/Event_Handling
You could do something like below.
Remember to be careful with App wide event listeners, you should always remove
those when you are done with them via the function below
Ti.App.removeEventListener("eventlistenername", eventfunctionname);
index.js
(function constructor() {
audioPlayer = Ti.Media.createAudioPlayer({
url: 'https://allthingsaudio.wikispaces.com/file/view/Shuffle%20for%20K.M.mp3/139190697/Shuffle%20for%20K.M.mp3',
allowBackground: true
});
audioPlayer.addEventListener('progress', function(e) {
Ti.API.info('Time Played: ' + Math.round(e.progress) + ' milliseconds');
});
audioPlayer.addEventListener('change', function(e) {
// set livebareText
var livebareText = 'State: ' + e.description + ' (' + e.state + ')';
// fire app wide event
Ti.App.fireEvent("app:updateLivebar",livebareText);
Ti.API.info('State: ' + e.description + ' (' + e.state + ')');
});
window = Alloy.createController('listen').getView();
window.open();
})();
livebar.js
$.livebar_playpausebtn.addEventListener('click', function(event) {
if (audioPlayer.playing || audioPlayer.paused) {
audioPlayer.stop();
if (Ti.Platform.name === 'android')
{
audioPlayer.release();
}
} else {
audioPlayer.start();
}
});
// Add App eventlistener to listen for updateSingleProgessBar
Ti.App.addEventListener("app:updateLivebar", updateLivebar);
function updateLivebar(livebarText){
$.livebar_datalbl.text = livebarText;
Ti.API.info('State: ' + e.description + ' (' + e.state + ')');
}

Render HTML with images using PhantomJS

I am trying to create a PDF from HTML text using PhantomJS (version 1.9.7). I've written a very simple script (made more complicated by error callbacks etc.)
phantom.onError = function(msg, trace) {
var msgStack = ['PHANTOM ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function + ')' : ''));
});
}
system.stdout.write(msgStack.join('\n'));
phantom.exit(1);
};
var page = require('webpage').create();
page.viewportSize = { width: 800, height: 600 };
page.paperSize = { format: 'A4', orientation: 'portrait', margin: '1cm' };
page.onResourceRequested = function(requestData, networkRequest) {
console.log('Request (#' + requestData.id + '): ' + JSON.stringify(requestData));
};
page.onResourceReceived = function(response) {
console.log('Response (#' + response.id + ', stage "' + response.stage + '"): ' + JSON.stringify(response));
};
page.onResourceError = function(resourceError) {
console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
};
page.onError = function(msg, trace) {
var msgStack = ['ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
console.error(msgStack.join('\n'));
};
page.content = "<html><body><b>test</b><img src=\"http://www.google.co.uk/images/srpr/logo11w.png\" alt=\"\" border=\"0\" /></body></html>";
page.render('tmp.pdf');
setTimeout(function() {
phantom.exit();
}, 5000);
I set up the page, assign the simple HTML string to the content property and render it to a PDF.
This script doesn't produce any output.
I've narrowed the problem down to the <img> element, when that is removed a PDF is generated as expected. I can see from the callback functions that the image is requested, a response is received, and there are no errors reported. I've tried rendering to a PNG which also yields no output.
I've explored the possibility of this being a proxy issue, however the raserize.js example works without any problems.
You have to call render when the page is fully loaded. Remember that loading a page via page.open or page.content is always async.
Change your code to this
page.content = "<html><body><b>test</b><img src=\"http://www.google.co.uk/images/srpr/logo11w.png\" alt=\"\" border=\"0\" /></body></html>";
setTimeout(function() {
page.render('tmp.pdf');
phantom.exit();
}, 5000);

Cannot read property 'opacity' of undefined

I am loading the fine uploader in this manner:
var uploader = new qq.FineUploaderBasic({
button: $("#docAddHref"),
request: {
endpoint: 'server/handleUploads'
},
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
sizeLimit: 204800 // 200 kB = 200 * 1024 bytes
},
callbacks: {
onSubmit: function (id, fileName) {
$messages.append('<div id="file-' + id + '" class="alert" style="margin: 20px 0 0"></div>');
},
onUpload: function (id, fileName) {
$('#file-' + id).addClass('alert-info')
.html('<img src="client/loading.gif" alt="Initializing. Please hold."> ' +
'Initializing ' +
'“' + fileName + '”');
},
onProgress: function (id, fileName, loaded, total) {
if (loaded < total) {
progress = Math.round(loaded / total * 100) + '% of ' + Math.round(total / 1024) + ' kB';
$('#file-' + id).removeClass('alert-info')
.html('<img src="client/loading.gif" alt="In progress. Please hold."> ' +
'Uploading ' +
'“' + fileName + '” ' +
progress);
} else {
$('#file-' + id).addClass('alert-info')
.html('<img src="client/loading.gif" alt="Saving. Please hold."> ' +
'Saving ' +
'“' + fileName + '”');
}
},
onComplete: function (id, fileName, responseJSON) {
if (responseJSON.success) {
$('#file-' + id).removeClass('alert-info')
.addClass('alert-success')
.html('<i class="icon-ok"></i> ' +
'Successfully saved ' +
'“' + fileName + '”' +
'<br><img src="img/success.jpg" alt="' + fileName + '">');
} else {
$('#file-' + id).removeClass('alert-info')
.addClass('alert-error')
.html('<i class="icon-exclamation-sign"></i> ' +
'Error with ' +
'“' + fileName + '”: ' +
responseJSON.error);
}
},
onError: function (id, name, reason, xhr) {
$('#fubErrorAlert .message').text(reason);
$('#fubErrorAlert button').click(function () {
$('#fubErrorAlert').hide();
});
$('#fubErrorAlert').show();
}
}
});
console.log('uploader called');
uploader();
When the page loads I am getting this javascript error:
Cannot read property 'opacity' of undefined
I installed the FineUploader via Nuget Pacakage for ASP.NET
https://github.com/Widen/fine-uploader-server/tree/master/ASP.NET%20MVC%20C%23
Please advice!
Your button option is likely the problem. You should change it to:
button: $("#docAddHref")[0]
If you want to do things like pass in a jQuery object, you will need to download and use Fine Uploader's jQuery plugin. More info about the plugin at http://docs.fineuploader.com/integrating/jquery.html

Debugging PhantomJS webpage.open failures

In PhantomJS, webpage.open takes a callback with a status parameter that's set to 'success' or 'fail'. According to the docs, it wll be "'success' if no network errors occurred, otherwise 'fail'." Is there a way to see the underlying network error that caused the failure?
The url I'm trying to load works fine when I put it in my browser, and when I take a screenshot after getting the 'fail' message I see the page that I was on before I called webpage.open (so I can't just ignore the fail). I'm using Phantom for testing, so ideally I'd like a robust way of easily getting a helpful error messsage when webpage.open fails (or better yet have it never fail!)
Found this post which explains how to set up callbacks to get at the underlying reason for the failure: http://newspaint.wordpress.com/2013/04/25/getting-to-the-bottom-of-why-a-phantomjs-page-load-fails/
Based on the that page, you could print out errors as follows:
page.onResourceError = function(resourceError) {
console.error(resourceError.url + ': ' + resourceError.errorString);
};
The page goes on to show an example of detailed logging for phantoms
var system = require('system');
page.onResourceRequested = function (request) {
system.stderr.writeLine('= onResourceRequested()');
system.stderr.writeLine(' request: ' + JSON.stringify(request, undefined, 4));
};
page.onResourceReceived = function(response) {
system.stderr.writeLine('= onResourceReceived()' );
system.stderr.writeLine(' id: ' + response.id + ', stage: "' + response.stage + '", response: ' + JSON.stringify(response));
};
page.onLoadStarted = function() {
system.stderr.writeLine('= onLoadStarted()');
var currentUrl = page.evaluate(function() {
return window.location.href;
});
system.stderr.writeLine(' leaving url: ' + currentUrl);
};
page.onLoadFinished = function(status) {
system.stderr.writeLine('= onLoadFinished()');
system.stderr.writeLine(' status: ' + status);
};
page.onNavigationRequested = function(url, type, willNavigate, main) {
system.stderr.writeLine('= onNavigationRequested');
system.stderr.writeLine(' destination_url: ' + url);
system.stderr.writeLine(' type (cause): ' + type);
system.stderr.writeLine(' will navigate: ' + willNavigate);
system.stderr.writeLine(' from page\'s main frame: ' + main);
};
page.onResourceError = function(resourceError) {
system.stderr.writeLine('= onResourceError()');
system.stderr.writeLine(' - unable to load url: "' + resourceError.url + '"');
system.stderr.writeLine(' - error code: ' + resourceError.errorCode + ', description: ' + resourceError.errorString );
};
page.onError = function(msg, trace) {
system.stderr.writeLine('= onError()');
var msgStack = [' ERROR: ' + msg];
if (trace) {
msgStack.push(' TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
system.stderr.writeLine(msgStack.join('\n'));
};