why is casper.on('click' ...) not triggering? - casperjs

Following is a minimal casper script that does a Google query. I've added casper.on('click' ...) prior to running the script, but it doesn't appear to get triggered.
What am I missing?
// File: google_click_test.js
"use strict";
var casper = require('casper').create();
casper.on('click', function(css) {
casper.echo('casper.on received click event ' + css);
});
// ================================================================
// agenda starts here
casper.start('https://google.com', function g01() {
casper.echo('seeking main page');
});
casper.then(function a02() {
casper.waitForSelector(
'form[action="/search"]',
function() {
casper.echo("found search form");
},
function() {
casper.echo("failed to find search form");
casper.exit();
});
});
casper.then(function a03() {
casper.fillSelectors('form[action="/search"]', {
'input[title="Google Search"]' : 'casperjs'
}, false);
});
casper.then(function a04() {
casper.click('form[action="/search"] input[name="btnG"]')
casper.echo('clicked search button');
});
casper.run();
Output:
Here's the output. I would expect to see casper.on received click event somewhere, but it seems that it didn't get triggered:
$ casperjs --ignore-ssl-errors=true --web-security=no google_click_test.js
seeking main page
found search form
clicked search button
$

Although your example runs fine for me using casperjs 1.1.0-beta3 and phantomjs 1.9.8, I've been having similar issues in the last few months with casperjs. Sadly it seems that the author has stopped maintaining the project. More information here:
https://github.com/n1k0/casperjs/issues/1299
I would suggest moving to a different testing framework. In my case I chose a combination of mocha + chai + nightmarejs. This gist is a good starting point:
https://gist.github.com/MikaelSoderstrom/4842a97ec399aae1e024

Related

How to post information in CasperJS

The following is the html I wanna tackle with.
I wanna post a query and see the weather reports for that city. I tried my codes:
var casper = require('casper').create();
var utils = require('utils');
casper.start('http://www.weather.com.cn/weather1d/101210101.shtml');
casper.waitForSelector('input', function()
{
this.fillXPath('div.search clearfix',{'//input[#id="txtZip"]':'shijiazhuang'},true);
});
casper.then(function()
{
utils.dump(this.getTitle());
});
casper.run();
It did not print the web paeg title on the console. I also tried this:
casper.waitForSelector('input', function()
{
this.fillSelectors('div.search clearfix',{'input[id="txtZip"]':'shijiazhuang'},true);
});
}
);
I did not get any web page title also. I got quite confused and did not what I had done wrong. Besides, it seems that this.fill method only tackles with name attributes to post information on CasperJS's official website. I need your help.
CasperJS script:
var casper = require('casper').create(), utils = require('utils');
casper
.start('http://www.weather.com.cn/weather1d/101210101.shtml',function(){
this
.wait(3000,function(){
this.capture('search.png');
utils.dump(this.getTitle());
})
.evaluate(function(){
document.getElementById('txtZip').value='shijiazhuang';
document.querySelector('input[type="button"]').click();
})
})
.run();
Result:
"【石家庄天气】石家庄今天天气预报,今天,今天天气,7天,15天天气预报,天气预报一周,天气预报15天查询"
search.png
You are doing it correct, you only have to modify your script a little bit.
Just modify the selector of the input field the actual don't seems to work, then you should get the correct result.
"this.fillXPath" only fills up the form and don't post it.
...
// fill the form
casper.waitForSelector('input', function() {
this.fillXPath('#txtZip', {
'//input[#id="txtZip"]': 'shijiazhuang'
}, true);
});
// trigger - post the form
casper.then(function() {
this.click('#btnZip');
});
// i can't speak chinese - wait for some specific change on this page
casper.wait(5000);
// take a screenshot of it
casper.then(function() {
this.capture("shijiazhuang_weather.png");
});
...

Running into Error while waiting for Protractor to sync with the page with basic protractor test

describe('my homepage', function() {
var ptor = protractor.getInstance();
beforeEach(function(){
// ptor.ignoreSynchronization = true;
ptor.get('http://localhost/myApp/home.html');
// ptor.sleep(5000);
})
describe('login', function(){
var email = element.all(protractor.By.id('email'))
, pass = ptor.findElement(protractor.By.id('password'))
, loginBtn = ptor.findElement(protractor.By.css('#login button'))
;
it('should input and login', function(){
// email.then(function(obj){
// console.log('email', obj)
// })
email.sendKeys('josephine#hotmail.com');
pass.sendKeys('shakalakabam');
loginBtn.click();
})
})
});
the above code returns
Error: Error while waiting for Protractor to sync with the page: {}
and I have no idea why this is, ptor load the page correctly, it seem to be the selection of the elements that fails.
TO SSHMSH:
Thanks, your almost right, and gave me the right philosophy, so the key is to ptor.sleep(3000) to have each page wait til ptor is in sync with the project.
I got the same error message (Angular 1.2.13). My tests were kicked off too early and Protractor didn't seem to wait for Angular to load.
It appeared that I had misconfigured the protractor config file. When the ng-app directive is not defined on the BODY-element, but on a descendant, you have to adjust the rootElement property in your protractor config file to the selector that defines your angular root element, for example:
// protractor-conf.js
rootElement: '.my-app',
when your HTML is:
<div ng-app="myApp" class="my-app">
I'm using ChromeDriver and the above error usually occurs for the first test. I've managed to get around it like this:
ptor.ignoreSynchronization = true;
ptor.get(targetUrl);
ptor.wait(
function() {
return ptor.driver.getCurrentUrl().then(
function(url) {
return targetUrl == url;
});
}, 2000, 'It\'s taking too long to load ' + targetUrl + '!'
);
Essentially you are waiting for the current URL of the browser to become what you've asked for and allow 2s for this to happen.
You probably want to switch the ignoreSynchronization = false afterwards, possibly wrapping it in a ptor.wait(...). Just wondering, would uncommenting the ptor.sleep(5000); not help?
EDIT:
After some experience with Promise/Deferred I've realised the correct way of doing this would be:
loginBtn.click().then(function () {
ptor.getCurrentUrl(targetUrl).then(function (newURL){
expect(newURL).toBe(whatItShouldBe);
});
});
Please note that if you are changing the URL (that is, moving away from the current AngularJS activated page to another, implying the AngularJS library needs to reload and init) than, at least in my experience, there's no way of avoiding the ptor.sleep(...) call. The above will only work if you are staying on the same Angular page, but changing the part of URL after the hashtag.
In my case, I encountered the error with the following code:
describe("application", function() {
it("should set the title", function() {
browser.getTitle().then(function(title) {
expect(title).toEqual("Welcome");
});
});
});
Fixed it by doing this:
describe("application", function() {
it("should set the title", function() {
browser.get("#/home").then(function() {
return browser.getTitle();
}).then(function(title) {
expect(title).toEqual("Welcome");
});
});
});
In other words, I was forgetting to navigate to the page I wanted to test, so Protractor was having trouble finding Angular. D'oh!
The rootElement param of the exports.config object defined in your protractor configuration file must match the element containing your ng-app directive. This doesn't have to be uniquely identifying the element -- 'div' suffices if the directive is in a div, as in my case.
From referenceConf.js:
// Selector for the element housing the angular app - this defaults to
// body, but is necessary if ng-app is on a descendant of <body>
rootElement: 'div',
I got started with Protractor by watching the otherwise excellent egghead.io lecture, where he uses a condensed exports.config. Since rootElement defaults to body, there is no hint as to what is wrong with your configuration if you don't start with a copy of the provided reference configuration, and even then the
Error while waiting for Protractor to sync with the page: {}
message doesn't give much of a clue.
I had to switch from doing this:
describe('navigation', function(){
browser.get('');
var navbar = element(by.css('#nav'));
it('should have a link to home in the navbar', function(){
//validate
});
it('should have a link to search in the navbar', function(){
//validate
});
});
to doing this:
describe('navigation', function(){
beforeEach(function(){
browser.get('');
});
var navbar = element(by.css('#nav'));
it('should have a link to home in the navbar', function(){
//validate
});
it('should have a link to search in the navbar', function(){
//validate
});
});
the key diff being:
beforeEach(function(){
browser.get('');
});
hope this may help someone.
I was getting this error:
Failed: Error while waiting for Protractor to sync with the page: "window.angular is undefined. This could be either because this is a non-angular page or because your test involves client-side navigation, which can interfere with Protractor's bootstrapping. See http://git.io/v4gXM for details"
The solution was to call page.navigateTo() before page.getTitle().
Before:
import { AppPage } from './app.po';
describe('App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should have the correct title', () => {
expect(page.getTitle()).toEqual('...');
})
});
After:
import { AppPage } from './app.po';
describe('App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
page.navigateTo();
});
it('should have the correct title', () => {
expect(page.getTitle()).toEqual('...');
})
});
If you are using
browser.restart()
in your spec some times, it throws the same error.
Try to use
await browser.restart()

Conditional execution of mocha test cases

I am using Mocha with Sinon JS and Phantom Js to test the google analytics call from a particular page. Till now, i am able to execute static test cases for individual element by writing different test case for each element. Like :
describe("Site Home Page Test", function() {
it ("Global Search track", function() {
var link = $('button.search');
link.click();
});
});
Now the ask is, is it possible to execute test case if only $('elem') is found? something like this:
describe("Site Home Page Test", function() {
// if(condition) {
it ("Global Search track", function() {
var link = $('button.search');
link.click();
});
// }
});
I'm not sure if I've missed the question completly, but you can do conditional test cases exactly how you have it written:
describe("Some module", function() {
if(false) {
it ("should NOT run this test case", function() { });
}
it("should run this test case", function() { });
});
mocha will only run the unit-test that isn't in the if-statement.
Some module
✓ should run this test case
1 passing (5 ms)

jplayer+Ajax inserted content

I am using jPlayer to play audio files.
If I use the player on content, which is privided, when the page gets loaded, it works without any problems.
I also need it for HTML which is inserted by AJAX. Here it does not work. It seems, that the ready event is not triggered.
I wrote a function, which can be executed by click(). In that way, I can click it manually, when the HTML which contains the player is fully loaded. Here I have the same problem: The ready event is not triggered.
This is my function which works on non ajax inserted players fine:
$('.jp-jplayer').each(function () {
var src = $(this).attr('data-src');
var id = $(this).attr('id');
var post_id = $(this).attr('data-id');
alert('beg');
$('#' + id).jPlayer({
ready: function () {
$(this).jPlayer('setMedia', {
mp3: "/prelisten/_lofidl/change_of_heart_full_lofi.mp3",
});
alert('#' + id);
},
swfPath: "/wp-content/themes/Dark_3Chemical_DE_mit_Pagenavi/Dark_3Chemical_DE/audioplayer/js",
//////ERRRROOOOOR
solution: "flash, html",
supplied: "mp3",
wmode: "window",
cssSelectorAncestor: "#jp_container_" + post_id,
play: function () { // To avoid both jPlayers playing together.
$(this).jPlayer("pauseOthers");
},
repeat: function (event) { // Override the default jPlayer repeat event handler
if(event.jPlayer.options.loop) {
$(this).unbind(".jPlayerRepeat").unbind(".jPlayerNext");
$(this).bind($.jPlayer.event.ended + ".jPlayer.jPlayerRepeat", function () {
$(this).jPlayer("play");
debug($(this));
});
} else {
$(this).unbind(".jPlayerRepeat").unbind(".jPlayerNext");
$(this).bind($.jPlayer.event.ended + ".jPlayer.jPlayerNext", function () {
//$("#jquery_jplayer_4858").jPlayer("play", 0);
});
}
},
});
$("#jplayer_inspector").jPlayerInspector({
jPlayer: $('#' + id)
});
});
Currently I am setting the src manually to exclude any possible errors here.
How can I get this function running on AJAX inserted content?
EDIT:
This is the code, which fetches the html including the players:
$.get('/query_posts.php', {
paged: _page,
cats: cols
}, function(data) {
$('#search-results').append(data).fadeIn(300);
//create_player_scripts();
//set_players();
$('#search-results').find('input[name="cartLink"]').each(function() {
$(this).val($(this).closest('.post1').find('.post_headl a').attr('href'));
});
});
To make an AJAX page reload work I had to first destroy all jplayer instances. So I wrote a little function that grabs all instances of a jplayer on the site (by looking for jp-audio classes) and calls jplayer('destroy'); and jplayer('clearMedia'). This function gets called in the $.ajax({ beforeSend: destroyJplayerInstances(); })
UPDATE:
Here is a statement from the developer of jPlayer, Mark Panaghiston:
https://groups.google.com/forum/#!topic/jplayer/Q_aRhiyYvQo
Hope that helps!

How do I focus on one spec in jasmine.js?

I have a bunch of failing specs from a rather large architectural change. I'd like to work on fixing them one by one by tagging each one with 'focus'.
Does jasmine.js have a feature like this? I swore I read at one point that it does but I don't see it in the docs.
When using Karma, you can enable only one test with fit or fdescribe (iit and ddescribe in Jasmine before 2.1).
This only runs Spec1:
// or "ddescribe" in Jasmine prior 2.1
fdescribe('Spec1', function () {
it('should do something', function () {
// ...
});
});
describe('Spec2', function () {
it('should do something', function () {
// ...
});
});
This only runs testA:
describe('Spec1', function () {
// or "iit" in Jasmine prior 2.1
fit('testA', function () {
// ...
});
it('testB', function () {
// ...
});
});
In core since 2.1 with fit and fdescribe.
You can run a single spec by using the url for the spec
describe("MySpec", function() {
it('function 1', function() {
//...
})
it('function 2', function() {
//...
}
})
Now you can run just the whole spec by this url http://localhost:8888?spec=MySpec and a the first test with http://localhost:8888?spec=MySpec+function+1
There are a few ways you can do it.
There is: Jasmine's feature Focused Specs (2.2): http://jasmine.github.io/2.2/focused_specs.html
Focusing specs will make it so that they are the only specs that run. Any spec declared with fit is focused.
describe("Focused specs", function() {
fit("is focused and will run", function() {
expect(true).toBeTruthy();
});
it('is not focused and will not run', function(){
expect(true).toBeFalsy();
});
});
However, I don't really like the idea of editing my tests (fit and fdescribe) to run them selectively. I prefer to use a test runner like karma which can filter out tests using a regular expression.
Here's an example using grunt.
$ grunt karma:dev watch --grep=mypattern
If you're using gulp (which is my favourite task runner), you can pass args into gulp-karma with yargs and match patterns by setting karma's config.
Kinda like this:
var Args = function(yargs) {
var _match = yargs.m || yargs.match;
var _file = yargs.f || yargs.file;
return {
match: function() { if (_match) { return {args: ['--grep', _match]} } }
};
}(args.argv);
var Tasks = function() {
var test = function() {
return gulp.src(Files.testFiles)
.pipe(karma({ configFile: 'karma.conf.js', client: Args.match()}))
.on('error', function(err) { throw err; });
};
return {
test: function() { return test() }
}
}(Args);
gulp.task('default', ['build'], Tasks.test);
See my gist: https://gist.github.com/rimian/0f9b88266a0f63696f21
So now, I can run a single spec using the description:
My local test run: (Executed 1 of 14 (skipped 13))
gulp -m 'triggers the event when the API returns success'
[20:59:14] Using gulpfile ~/gulpfile.js
[20:59:14] Starting 'clean'...
[20:59:14] Finished 'clean' after 2.25 ms
[20:59:14] Starting 'build'...
[20:59:14] Finished 'build' after 17 ms
[20:59:14] Starting 'default'...
[20:59:14] Starting Karma server...
INFO [karma]: Karma v0.12.31 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
WARN [watcher]: All files matched by "/spec/karma.conf.js" were excluded.
INFO [Chrome 42.0.2311 (Mac OS X 10.10.3)]: Connected on socket hivjQFvQbPdNT5Hje2x2 with id 44705181
Chrome 42.0.2311 (Mac OS X 10.10.3): Executed 1 of 14 (skipped 13) SUCCESS (0.012 secs / 0.009 secs)
[20:59:16] Finished 'default' after 2.08 s
Also see: https://github.com/karma-runner/karma-jasmine
For anyone stumbling upon this, a better approach, which you can set up from the code itself, is to use this plugin: https://github.com/davemo/jasmine-only
It allows you set the spec exclusivity right on the code like this:
describe.only("MySpec", function() {
it('function 1', function() {
//...
})
it.only('function 2', function() {
//...
}
})
// This won't be run if there are specs using describe.only/ddescribe or it.only/iit
describe("Spec 2", function(){})
There has been a long discussion to get this added to Jasmine core, see: https://github.com/pivotal/jasmine/pull/309
If you happen to be using Jasmine via Karma/Testacular you should already have access to ddescribe() and iit()
You can create your all your specs up front but disable them with xdescribe and xit until you're ready to test them.
describe('BuckRogers', function () {
it('shoots aliens', function () {
// this will be tested
});
xit('rescues women', function () {
// this won't
});
});
// this whole function will be ignored
xdescribe('Alien', function () {
it('dies when shot', function () {
});
});
This is the most simplified answer with a practical example .Even in fdescribe you can run few it blocks using it. f means focus.
Also in a none fdescribe block which is just describe, you can select only specific it blocks by marking them as fit.
Please run the below code and observe the console log, also read the comments in the code.
Read this author's article it helps too . https://davidtang.io/2016/01/03/controlling-which-tests-run-in-jasmine.html
//If you want to run few describe only add f so using focus those describe blocks and it's it block get run
fdescribe("focus description i get run with all my it blocks ", function() {
it("1 it in fdescribe get executed", function() {
console.log("1 it in fdescribe get executed unless no fit within describe");
});
it("2 it in fdescribe get executed", function() {
console.log("2 it in fdescribe get executed unless no fit within describe");
});
//but if you and fit in fdescribe block only the fit blocks get executed
fit("3 only fit blocks in fdescribe get executed", function() {
console.log("If there is a fit in fdescribe only fit blocks get executed");
});
});
describe("none description i get skipped with all my it blocks ", function() {
it("1 it in none describe get skipped", function() {
console.log("1 it in none describe get skipped");
});
it("2 it in none describe get skipped", function() {
console.log("2 it in none describe get skipped");
});
//What happen if we had fit in a none fdescribe block will it get run ? yes
fit("3 fit in none describe get executed too eventhough it;s just describe ", function() {
console.log("3 fit in none describe get executed too");
});
});
With stand-alone Jasmine(2.0.0), on the spec_runner.htlm, I could click a specific spec and focus on that one spec. I should have noticed this feature earlier.
Not exactly what you've asked for but adding iit will test only that particular spec and ignore all others in the file, ddescribe works in the same way. So you can focus on a particular spec using iit or ddescribe

Resources