Debug output in tests - javascript

How do I output some information in Postman tests?
console.log(tv4.error);
tests["Valid Data1"] = tv4.validate(data1, schema);
console.log() seems to be working but I want to output my info into the same panel where my assertions go (for easier correlation):

Just make a fake test that passes:
var jsonData = JSON.parse(responseBody);
tests["id = " + jsonData.id] = true; // debug message
tests["name = " + jsonData.name] = true; // debug message

Reference for the people who just want to use Chrome’s Developer Tools (which will let you see console output and give you many more features)
To enable it
Type chrome://flags inside your Chrome URL window
Search for "Debugging for packed apps" setting
Enable the setting
Restart Chrome
You can access the Developer Tools window by right clicking anywhere inside Postman and selecting "inspect element".
You can also go to chrome://inspect/#apps and then click "inspect"
Reference

I used this, which isn't the prettiest, but it works for what I needed.
tests["your test name here " + data.data.length] = data.data.length > 100;

Piggybacking on the other answers, just define a function in your Postman test code
var print = function(s){
tests[s] = true;
};
then consume it like
print("current value of x: " + x);

Now You have got sth called "Postman Console" To run it please type CTRL + ALT + C
For mor info see here: https://blog.getpostman.com/2016/08/26/the-postman-console/

One of the way is use the tests[""+value].
e.g
http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=Your_API_Key.
Response :

Similar to a previous answer regarding an alternate option: using dev tools. However, if you are using the native app, right clicking to get the dev tools won't work.
Instead,
Head to View in the application menu, and click on "Show DevTools".
In the DevTools window, clicking on the top level Console tab should show the app’s debug logs.
Reference: https://learning.getpostman.com/docs/postman/collection_runs/debugging_a_collection_run

Related

Is it possible to avoid breaking on a debugger statement in Chrome?

I'm trying to reverse engineer a heavily obfuscated JS and one of the tricks the author does is to continuously call the debugger statement from within an anonymous function:
Unfortunately, I cannot right click and Never pause it, because each time the function is called a new anonymous function is spawned. The only way for me to inspect the code with DevTools open is to toggle the Disable all breakpoints button, but that disables my breakpoints too.
Is there any way to disable exclusively all debugger statements in Chrome?
In case there isnt, what could be done to bypass this anti-tampering trick?
Download the offending webworker.js file to your local drive, and use a text editor to replace all occurrences of "debugger" with ";".
Then use a Chrome extension to replace the remote resource with your local modified version.
https://chrome.google.com/webstore/detail/resource-override/pkoacgokdfckfpndoffpifphamojphii?hl=en
FYI: I do not endorse the above extension. It was just the first I found via Google.
This answer is for an old Chrome prior to 2021 where we could hack the internals of devtools itself by using devtools-on-devtools:
undock devtools into a separate window
press the full devtools hotkey - CtrlShifti or ⌘⌥i
paste the following code in this new devtools window console and run it
{
const rx = /\bdebugger\b/y;
const eventSymbol = SDK.DebuggerModel.Events.DebuggerPaused;
const original = [...SDK.targetManager._modelListeners.get(eventSymbol)]
.find(v => v.listener.name === '_debuggerPaused');
const debuggerModel = SDK.targetManager.models(SDK.DebuggerModel)[0];
SDK.targetManager.removeModelListener(
SDK.DebuggerModel,
eventSymbol,
original.listener,
original.thisObject);
SDK.targetManager.addModelListener(
SDK.DebuggerModel,
eventSymbol,
async function({data}) {
if (data._debuggerPausedDetails.reason === 'other') {
const frame = data._debuggerPausedDetails.callFrames[0];
const code = await frame._script.requestContent();
let {columnNumber: x, lineNumber: y} = frame._location;
let pos = 0;
while (y--)
pos = code.indexOf('\n', pos) + 1;
rx.lastIndex = Math.max(0, pos + x);
if (rx.test(code)) {
debuggerModel.resume();
return;
}
}
original.listener.apply(original.thisObject, arguments);
});
}
Notes:
You can save this code as a snippet in devtools to run it later.
To quickly switch docking mode in the main devtools press CtrlShiftD or ⌘⇧D
Theoretically, it's not that hard to put this code into resources.pak file in Chrome application directory. There are several tools to decompile/build that file so just add the code to any script that has something like SDK.DebuggerModel.Events.DebuggerPaused inside. One can even write a tool that does that automatically on Chrome update.
Right-click the in the gutter on the line with the debugger statement and select "Never pause here".

How to see results of console.profile()?

According to Chrome Console API Reference and MDN Docs, using console.profile('label') to start profiling and later using console.endProfile() to end profiling, should result in a profile added to Profiles (has been since renamed to Performance) panel in Chrome.
This works for me in Firefox, but I don't get any profiles when I run my code in Chrome. Instead I get the warning:
DevTools: CPU profile parser is fixing 16 missing samples.
Am I missing something here or is this a bug in Chrome DevTools?
Turns out the profile goes into a different panel:
CPU profiles added to the JavaScript profiler panel. You can open it by clicking three dots menu (in the top right corner)
⋮-> More tools -> JavaScript Profiler.
The profiling can be observed from below code part.
function profileTest(callback) {
let i = 0;
let work = setInterval(function() {
if(i == 3) {
callback();
clearInterval(work);
return;
}
console.log('Doing some work..');
i = i + 1;
}, 1000);
}
console.profile("profileTest()");
profileTest(function(){
console.profileEnd();
});
Note: setInterval is used for simulation purpose.
As #atavakoli have already answered, created profile can be seen in 'CPU PROFILES' part in 'Javascript Profiler' tab that can be opened from Developer Tools → Three dots → More tools. For example below screenshot shows the result profile of above code part.
See following link: https://developers.google.com/web/updates/2016/12/devtools-javascript-cpu-profile-migration
For the warning message, below question link can be referred.
Chrome: CPU profile parser is fixing n missing samples

console output does not appear in code wars

I'm doing some javascript exercises on code wars. I want to see what's going wrong in my programs by printing to the console, but nothing except the test results appears in the output window. Does anyone know how to print to the console in code wars? I can't find anything in their documentation.
function areYouPlayingBanjo(name) {
// Implement me
var person = name.split('');
person[0].toLowerCase();
console.log(person[0]);
if(person[0] === 'r'){
return name + " plays banjo";
}
else{
return name + " does not play banjo";
}
}
This is not exactly an answer to the question, but more of an extended answer in order to document a chrome extension that can allow debugging in the console for codewars.
Install this chrome extension:
https://github.com/bojan88/Codewars-JavaScript-debugger
This allows you to use the debugger; statement to force the your code to run in the browser rather than the sandboxed environment on the codewars servers. Works great.
Caveat: I don't know if this is safe. Use at your own risk.
This worked for me:
Console.Out.WriteLine("Print stuff to output here.");

javascript. formatting console.log

I´m working on a big angular.js project.
Now, I´ve to profile some pages about the performance.
With the console.log of the project I´m looking for the performance problems.
I miss if console.log can output the current time (yes, I know in Chrome you can set up).
Is there a way (like in log4java) to format the output?
Thanks in advance,
Be careful, the console object should not be activated in production mainly because it can breaks the code for some users (for example IE8 or less users).
But if you want to test on a tool that you know, you can use the Web API interface which provides some useful method on this object:
https://developer.mozilla.org/en-US/docs/Web/API/Console
(This doc is from the Mozilla Developer Network (MDN) and therefore mainly applies to Firefox, but at the end of that page you can find links to the corresponding docs for the IE, Chrome and Safari DevTools as well as Firebug).
For example, you can use the time() method for your use case:
console.time("answer time");
// ... some other code
console.timeEnd("answer time");
Outputs something like this:
You could try something like this:
console = window.console ? console : {};
native_log = console.log;
window.console.log = function myConsole() {
// Cannot log if console.log is not present natively,
// so fail silently (in IE without debugger opened)
if (!native_log)
return;
var args = Array.prototype.slice.call(arguments);
args.unshift(new Date());
native_log.apply(console, args);
}
console.log('hello'); // Date 2014-12-02T14:14:50.138Z "hello"
Of course, you would not let the new Date() as is, but it gives you the idea.

Controlling a Firefox Extension via Javascript

Is it possible, using javascript, to control an overlay firefox extension? I've extracted the contents of the extension and have identified what functions/methods I need to run, but they are not accessible within the scope of the console.
Thanks in advance for any ideas.
Yes it possible to interact with other add-ons, given the right circumstances.
My test case here will be com.googlecode.sqlitemanager.openInOwnWindow(), which is part of the SqliteManager addon.
In newer builds (I'm using Nightly), there is the Browser Toolbox. With it is is as simple as opening a toolbox and executing com.googlecode.sqlitemanager.openInOwnWindow() in the Console.
You may instead use the Browser Console (or any chrome enabled WebDev Console for that matter, e.g. the Console of "about:newtab"). But you need some boilerplate code to first find the browser window. So here is the code you can execute there: var bwin = Services.wm.getMostRecentWindow("navigator:browser"); bwin.com.googlecode.sqlitemanager.openInOwnWindow()
Again, enable chrome debugging. Then open a Scratchpad and switch to Chrome in the Environment menu. Now executing com.googlecode.sqlitemanager.openInOwnWindow() in our Scratchpad will work.
You may of course write your own overlay add-on.
As a last resort, patch the add-on itself.
Bootstrapped/SDK add-ons: you can load XPIProvider.jsm (which changed location recently) and get to the bootstrapped scope (run environment of bootstrap.js) via XPIProvider.bootstrapScopes[addonID], and take it from there (use whatever is in the bootstrap scope, e.g. the SDK loader).
Now about the right circumstances: If and how you can interact with a certain add-on depends on the add-on. Add-ons may have global symbols in their overlay and hence browser window, such as in the example I used. Or may use (to some extend) JS code modules. Or have their own custom loader stuff (e.g. AdBlock Plus has their own require()-like stuff and SDK add-ons have their own loader, which isn't exactly easy to infiltate)...
Since your question is rather unspecific, I'll leave it at this.
Edit by question asker: This is correct, however I figured I'd add an example of the code I ended up using in the end, which was in fact taken directly from mozilla's developer network website:
In my chrome js:
var myExtension = {
myListener: function(evt) {
IprPreferences.setFreshIpStatus(true); // replace with whatever you want to 'fire' in the extension
}
}
document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true);
// The last value is a Mozilla-specific value to indicate untrusted content is allowed to trigger the event.
In the web content:
var element = document.createElement("MyExtensionDataElement");
element.setAttribute("attribute1", "foobar");
element.setAttribute("attribute2", "hello world");
document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("MyExtensionEvent", true, false);
element.dispatchEvent(evt);
Update for Firefox 47 and up
Things changed drastically in Firefox 47. This is the new way to access it.
var XPIScope = Cu.import('resource://gre/modules/addons/XPIProvider.jsm');
var addonid = 'Profilist#jetpack';
var scope = XPIScope.XPIProvider.activeAddons.get(addonid).bootstrapScope
Old way for < Firefox 47
Update for methods of today
Typically you will do so like this:
If i wanted to get into AdBlocks scope, I check AdBlock id, it is {d10d0bf8-f5b5-c8b4-a8b2-2b9879e08c5d} so I would go:
var XPIScope = Cu.import('resource://gre/modules/addons/XPIProvider.jsm');
var adblockScope = XPIScope.XPIProvider.bootstrapScopes['{d10d0bf8-f5b5-c8b4-a8b2-2b9879e08c5d}'];
You can now tap into anything there.
Another example, I have an addon installed with id NativeShot#jetpack
I would tap into it like this:
var XPIScope = Cu.import('resource://gre/modules/addons/XPIProvider.jsm');
var nativeshotScope = XPIScope.XPIProvider.bootstrapScopes['NativeShot#jetpack'];
if you do console.log(nativeshotScope) you will see all that is inside.

Categories

Resources