How to set test case fail and pass messages in Casper js? - javascript

How I can set two different test messages for fail and pass test cases and after running all test cases how I can get list of all fail and pass messages which I can print in log file or xml file.
What is better way to store all messages and get in correct format.
Here is my Sample Home page.js
HomePage = function () {
var PageTestParams = TestParams.Modules.HomePage,
PageLangText = Lang.Modules.HomePage;
SearchResult = function(test){
},
SearchTextField = function(test){
test.assertExists(PageTestParams.SearchFormSelector, PageLangText.SuccessMsg["SearchForm"]);
SearchResult(test);
},
NavigationCount = function(test){
test.assertElementCount(PageTestParams.NavigationSelector, PageTestParams.NavigationCount,PageLangText.SuccessMsg["NavigationCount"]);
SearchTextField(test);
},
CheckTitle = function(test){
test.assertTitle(PageTestParams.Title, PageLangText.SuccessMsg["TitleText"]);
casper.test.pass("main fail ho gaya");
NavigationCount(test);
},
this.init = function(test){
CheckTitle(test);
}
};
I am passing this JS for test assertion if any test case fail or pass the same message is getting printed for same scenario. I have searched and got below syntax but its printing same message which I have setted in test assertion.
casper.test.on("fail", function(failure) {
casper.echo("FAIL " + failure.message);
});

To get two different messages when using a single test is something I have personally not come across yet. If you want a way to work around it you could do something like:
var x=4;
if(x>2){
casper.test.pass("PASS Message.");
}else{
casper.test.fail("FAIL Message.");
}
You could manipulate the if statement to have a boolean or whatever else you may like, but this seems like the most obvious way I would do it.
As for getting a list of all passing and failing messages, the extent I know about that is that there are the getFailures(); and a getPasses(); methods, these may or may not be what your looking for, but maybe they can help get you started! Good Luck!

You can do something like this (same logic for success or fail):-
var successes = [];
casper.test.on("success", function(success) {
successes.push(success);
});
Then on casper.run you can do a couple of things:-
1) To see the full dump of all successes (you can see all the properties) you can do this:-
casper.run(function () {
test.done();
require('utils').dump(successes);
});
2) to output the array of successes one by one (so you can format the output) you can do:-
casper.run(function () {
test.done();
successes.forEach(function(item){
casper.echo(item.standard);
});
});
3) I assume you know you can also output the full test assertions to xunit by passing in --xunit=output.xml

Related

Why is Meteor Mongo collection inaccessible on the client?

I have a piece of code show below that creates a Mongo collection as show below. However whenever I try to access the collection from inside of the Meteor.isClient scope I get an error. Please can anyone spot my mistake.
ImagesCollection = new Mongo.Collection("Images");
Images = new Mongo.Collection("Images");
if(Meteor.isClient){
Template.body.helpers({ images :
function() {
console.log("Template Loade");
return Images.find({},{sort: -1 });
}
}) ;
Template.Images.events({
'click .js-image' : function(event){
$(event.target).css("Width", "50px");
} ,
'click .js-del-image' : function(event){
var image_id = this._id ;
$("#"+image_id).hide({slow });
Images.remove({"_id" : image_id});
},
'click .js-rate-image' : function(event){
var rating = $(event.currentTarget).data("userrating");
var image_id = this.id ;
Images.find({"_id": image_id});
}
});
}
The content of my Startup.js is as below as well
if(Meteor.isServer){
Meteor.startup(function(){
for(var i = 0 ; i<=23 ; i++)
{
Images.insert({
'img_src' : 'img_'+i+'.jpg' ,
'img_alt' : 'Image number' + i
});
console.log(Images.find().count);
}
});
}
consle.log("Template Loade");
Since you don't specify your error, the line above will raise an error.
From the code that you have provided, there are two problems that I can see.
First, in your images template helper, your second parameter for the Images.find() function call is incorrect. You are missing a document field specification for the sort operation. This second parameter needs to be in the format {sort: {'document_field': -1}}. Although you have not provided the error text that you are seeing, I suspect the error has something to do with Mongo not being able to process the query, and this would be the reason for that.
Second, although this is less severe and should not be causing the problems with your inability to access the Images collection on the client, in your console.log() statement in your server Meteor.startup() code you are accessing count as if it is a property on the cursor returned from the Images.find() function call. In actuality, it is a function and should be called like so: Images.find().count().
Also, as an aside, I would suggest that you give different names to your two collections that you have defined. Giving them both the same name may cause issues for you if you are trying to manipulate data through the Mongo shell.
I am not sure if this is an issue, but why are you initializing twice the "images" collection ?
ImagesCollection = new Mongo.Collection("Images");
Images = new Mongo.Collection("Images");
And ImagesCollection is not used anywhere in you're code.
Try to remove one of this lines.

Pass function to alertify.js

Im knocking my head to this scripts and I cant get my function to be displayed inside the Aletify.js alerts.
Some help will be incredibly helpful ;-)
The Function:
Oshoplang = {
// System Message Text
RemoveError: '<p>This item has now been removed from your cart.\n\nThank you.',
Added: 'Has now been added to your cart',
OutOfStock: '<p>This item is not currently available or is out of stock.</p>',
PreOrder: '<p>Your pre-order has been made successfully.\n\nThank you.</p>',
InvalidQuantity: '<p>It looks like you entered an invalid quantity.\n\nPlease try again.</p>',
}
window.alert = function() {};
$("#confirm-else").on('click', function() {
reset();
$('#e-content').addClass('blur');
alertify.alert(Oshoplang, function(e) {
if (e) {
alertify.success("OK");
$('#e-content').removeClass('blur');
location.reload();
} else {
alertify.error("You've clicked Cancel");
}
});
return false;
});
I normally don't get a message on the run, but this way but i believe i'm close somewhere :-)
Not sure if you're still having this issue, but I believe that the alertify.alert function doesn't have any callbacks, as it's just a way to show a message. You're probably looking for the alertify.confirm instead.
The message is also not showing up because the first argument to alertify.alert or alertify.confirm needs to be a string. In your example, you're passing an object.
I've set up a demo of your code which has been adjusted to work on here on JSFiddle.
For what it's worth, the code sample is using an older version of alertify (0.3) and it has been updated, so that version 1 which is now out would have a somewhat adjusted syntax.

Passing variables between "pipes" in Gulp

I'm trying to write a gulp tasks that takes some user input via the gulp-prompt plugin. But I'm having trouble passing that input along to other eg:
gulp.task('userinput', function(){
var myVar = 'MONKEY';
gulp.src('./templates/_component.*')
.pipe(prompt.prompt([
{
type: 'input',
name: 'userInput',
message: 'Say something'
}
], function(res){
myVar = res.userInput;
}))
.pipe(prompt.confirm('You said ' + myVar));
});
Assuming I enter hello at the prompt, I was expecting the confirmation to say You said Hello, but it says You said MONKEY.
Is this possible with Gulp?
The issue here is that you are creating the second prompt ('You said ' + myVar) before the first prompt has been executed:
Set myVar to 'MONKEY'
Create streams
Create src stream, which is asynchronous
Create first prompt, and add it to the src stream
Create second prompt using current value of myVar, and add it to the first prompt stream
Only now are the streams executed processed
Load sources
Run first prompt, set the myVar
Run the second prompt using previously generated message
The only solution if you want to keep it all as a single stream is to use the variable within something that allows for a closure (function). Some plugins already accept a closure as an argument, but most don't.
One solution to wrap a stream in a closure that would work here is gulp-tap, which isn't designed for this scenario specifically, but should work. it looks like this:
var tap = require('gulp-tap');
//...
gulp.task('userinput', function(){
var myVar = 'MONKEY';
gulp.src('./templates/_component.*')
.pipe(prompt.prompt([
{
type: 'input',
name: 'userInput',
message: 'Say something'
}
], function(res){
myVar = res.userInput;
}))
.pipe(tap(function(file, t) {
// format is t.through(stream-function, [arguments...])
return t.through(prompt.confirm, ['You said ' + myVar]);
});
});
Because this is wrapped in a closure, and evaluated for each file, it will pick up the current value for the variable. However, because it works on each file, you'll see the prompt once for each file processed.
An better solution would be to separate your task into multiple, dependent tasks. That would look something like this:
var myVar = 'MONKEY';
gulp.task('userinput1', function(){
return gulp.src('./templates/_component.*', {read: false})
.pipe(prompt.prompt([
{
type: 'input',
name: 'userInput',
message: 'Say something'
}
], function(res){
myVar = res.userInput;
}));
});
gulp.task('userinput', ['userinput1'], function() {
return gulp.src('./templates/_component.*')
.pipe(prompt.confirm('You said ' + myVar));
});
Now the first task (userinput1) will run and complete before the second one is processed (userinput2), so the variable will be set correctly.
NOTE: Make sure you return the stream from your tasks, otherwise they are processed synchronously, and your variable won't get set.
Finally, it might make more sense to forgo the gulp-prompt task altogether, because it doesn't really have much to do with the stream. You'd probably be better off using straight Node JavaScript within your task to gather the user's input (preferably in a synchronous manner), then processing your files in a gulp-stream after that.

How do I call a function stored in a jQuery array?

I have an array of hooks in jQuery that are executed before I load data into a grid. In one case, however, I want to remove the hook, then add it back for later. Whatever I'm doing is not working just right... it's probably a syntax error because I'm still somewhat new to jQuery. Any help would be appreciated, thanks!
Current code:
var preLoad = this.opts.hooks.preLoad.pop();
//stuff happens
//now I want to add the preLoad hook back
this.opts.hooks.preLoad.push(function(report) { preLoad(report); });
EDIT
It turns out the issue lies elsewhere in the code. However, I'd still like to know how best to accomplish this.
You access it the same way as any other variable stored in any other array.
this.opts.hooks.preLoad[0](myReport)
Can you not just add the function you removed like this?
var preLoad = this.opts.hooks.preLoad.pop();
//stuff happens
//now I want to add the preLoad hook back
this.opts.hooks.preLoad.push(preLoad);
And are you sure it's always the last one in the array that you want to remove?
It probably has to do with the fact that you are "canning" the argument "report" when you push the function back on the stack.
Try doing it like that:
var preLoad = this.opts.hooks.preLoad.pop();
//stuff happens
//now I want to add the preLoad hook back
this.opts.hooks.preLoad.push(preLoad);
I've tested it here http://jsfiddle.net/fWRez/
The example you gave has nothing to do with jQuery and is pure Javascript. Also, beware that what you are doing in your example is... not right. Consider this :
var ReportManager {
...
replace: function(report) {
var preLoad = this.opts.hooks.preLoad.pop();
//stuff happens
//now I want to add the preLoad hook back
this.opts.hooks.preLoad.push(function(report) { preLoad(report); });
}
}
If you execute this :
replace(null);
replace({foo:'bar'});
replace(null);
Your this.opts.hooks.preLoad array will look like this :
Array(
0: function(report) { return function(report) { return function(report) { ... } } }
)
Because you are pushing the function wrapped into itself every time you execute your code. I'm not sure why you need to pop and push it back in again, but this just look odd.
Also, Javascript is a very flexible language; which mean that you can do many weird stuff, like
"hello".concat(" world"); // -> 'hello world'
0.toString(); // -> '0'
(function(a) { return a; })("foo"); // -> 'foo'
(function() { return false; })() || (function() { return true; })(); // -> true (executes both functions)
(function(i) { return [i*2,i*3,i*4]; })(2)[1]; // -> 6
$('selector')[0]; // ...
// etc.

Is there a way to filter output in Google Chrome's console?

I'm getting a lot of noise from the output of the 3rd party's page i'm currently playing with and i wonder if there's a way to filter the output on the console. Something like Logcat's flags. Is there a way to do that?
EDIT
I found a way to disable the output that was causing the biggest ammount of noise. I clicked with the right-clicked on the console and then disabled the XMLHttpRequest Logging option. It's not what i wanted, but it's what i needed.
You can use regular expressions.
For example to exclude the word browser-sync I use ^((?!browser-sync).)*$.
See also here
Chrome 44.0.2403.125
Going further than the above answer comments..
Go in console mode ( Control Shift J on Windows ) , enter this :
console.nativeLog = console.log;
Then enter this
console.log = function( a, b ){ if(a=="extension") console.nativeLog( b ) }
The first line keeps the native implementation in a safe spot.
The second line does pretty much what you request.
Works for me.
I just blogged about my solution to this. I modified Ben Alman's "ba-debug" library and made a modular "Trace" object designed to be used with different modules or areas of the code (defined by you).
Basic usage:
var _trace = new Trace('ModuleName');
Then, when you want to trace out any level of diagnostics, you do:
_trace.error('error level message');
_trace.warn('warning level message');
_trace.info('information level message');
_trace.log('log level message');
_trace.debug('debug level message');
Then, in your page, or in your console, you can do this:
Trace.traceLevel('ModuleName', Trace.Levels.warn);
Here's my blog post for more detail and the JavaScript file:
If you have control of both the page and extension scripts then you can run both through your own function. In that function you could now control output.
var pageErrors = true;
var extErrors = true;
function outputToConsole(message, sender) {
if (sender == 'page' && pageErrors) { console.write(message); }
if (sender == 'ext' && extErrors) { console.write(message); }
}
Everywhere you want to log replace console.log with outputToConsole()
This is what I just wrote to solve the same problem. Compared to the previous answers, it has the benefit of properly handling multiple arguments to console.log and of preventing the absence of window.console.log to throw uncaught exceptions.
(function(){
window.console = window.console||{log:0};
var nativeLog = window.console.log;
window.console.log = function() {
try {
// these conditions find all console.log output
// from bitcoinjs-0.1.3 but not much else
// (who else ends an extremely short first parameter with a space?)
if ((arguments.length == 2)
&& (arguments[0].length <= 5)
&& (arguments[0].slice(-2) === ': ')
) {
return;
};
nativeLog.apply(window.console, arguments);
} catch(e) {};
};
})();
If regular expressions aren't your thing, there are two other things that you can do:
In the Filter input box you can add a string of negative matches that will prevent messages beginning with those characters from displaying.
Example:
-WARNING -Errorcode -bonk
Will suppress messages like the following:
WARNING line 234 something else on this line
This message will still display
Errorcode 234: Some error that will be hidden
bonk
The only message from the above that would display is:
This message will still display
ANOTHER simple thing you can do is to right-click on any line in the console log and choose the first option from the pop-up context menu: "Hide messages from ___________" (some script name). This will hide all error messages produced by that script.
To "unhide" those messages again, note that the undesired script was added into the Filter input box - just delete it from there and the messages will return.

Categories