{"id":10953,"date":"2013-01-28T09:00:00","date_gmt":"2013-01-28T08:00:00","guid":{"rendered":"http:\/\/pjagielski.github.com\/2013\/01\/28\/caspers-for-java-developers"},"modified":"2022-08-02T12:47:19","modified_gmt":"2022-08-02T10:47:19","slug":"casperjs-for-java-developers","status":"publish","type":"post","link":"https:\/\/touk.pl\/blog\/2013\/01\/28\/casperjs-for-java-developers\/","title":{"rendered":"CasperJS for Java developers"},"content":{"rendered":"<h2 id=\"why-casperjs\">Why CasperJS<\/h2>\n<p>Being a Java developer is kinda hard these days. Java <a href=\"http:\/\/1.bp.blogspot.com\/-GLkCsR5eEIA\/TXELWvpXsEI\/AAAAAAAAACc\/Oym-S4t7nSc\/s1600\/java-is-dead.png\">may not be dead yet<\/a>, but when keeping in sync with all the hipster JavaScript frameworks could make us feel a bit outside the playground. It\u2019s even hard to <a href=\"http:\/\/devrates.com\/project\/list?query=%5Bjavascript%5D\">list<\/a> <a href=\"http:\/\/jster.net\/\">JavaScript<\/a> <a href=\"http:\/\/todomvc.com\/\">frameworks<\/a> with latest releases on one website.<\/p>\n<p>In my current project, we are using <a href=\"http:\/\/angularjs.org\/\">AngularJS<\/a>. It\u2019a a nice abstraction of MV* pattern in frontend layer of any web application (we use Grails underneath). <a href=\"http:\/\/thesmithfam.org\/blog\/2012\/12\/02\/angularjs-is-too-humble-to-say-youre-doing-it-wrong\/\">Here<\/a> is a nice article with an 8-point Win List of Angular way of handling AJAX calls and updating the view. So it\u2019s not only a funny new framework but a truly helper of keeping your code clean and neat.<\/p>\n<p>But there is also another area when you can put helpful JS framework in place of plan-old-java one &#8211; functional tests. Especially when you are dealing with one page app with lots of asynchronous REST\/JSON communication.<\/p>\n<h2 id=\"selenium-and-geb\">Selenium and Geb<\/h2>\n<p>In Java\/JVM project the typical is to use <a href=\"http:\/\/seleniumhq.org\/\">Selenium<\/a> with some wrapper like <a href=\"http:\/\/www.gebish.org\/\">Geb<\/a>. So you start your project, setup your CI-functional testing pipeline and\u2026 after 1 month of coding your tests stop working and being maintainable. The frameworks itselves are not bad, but the typical setup is so heavy and has so many points of failure that keeping it working in a real life project is really hard.<\/p>\n<p>Here is my list of common myths about Selenium:<br \/>\n* <em>It allows you to record test scripts via handy GUI<\/em> &#8211; maybe some static request\/response sites. In modern web applications with asynchronous REST\/JSON communication your tests must contain a lot of \u201cwaitFor\u201d statements and you cannot automate where these should be included.<br \/>\n* <em>It allows you to test your web app against many browsers<\/em> &#8211; don\u2019t try to automate IE tests! You have to manually open your app in IE to see how it actually bahaves!<br \/>\n* <em>It integrates well with continuous integration servers like Jenkins<\/em> &#8211; you have to setup Selenium Grid on server with X installed to run tests on Chrome or Firefox and a Windows server for IE. And the headless HtmlUnit driver lacks a lot of JS support.<\/p>\n<p>So I decided to try something different and introduce a bit of JavaScript tooling in our project by using CasperJS.<\/p>\n<h2 id=\"introduction\">Introduction<\/h2>\n<p><a href=\"http:\/\/casperjs.org\/\">CasperJS<\/a> is simple but powerful navigation scripting &amp; testing utility for <a href=\"http:\/\/phantomjs.org\/\">PhantomJS<\/a> &#8211; scritable headless WebKit (which is an rendering engine used by Safari and Chrome). In short &#8211; CasperJS allows you to navigate and make assertions about web pages as they\u2019d been rendered in Google Chrome. It is enough for me to automate the functional tests of my application.<\/p>\n<p>If you want a gentle introduction to the world of CasperJS I suggest you to read:<br \/>\n* <a href=\"http:\/\/casperjs.org\/\">Official website<\/a>, especially <a href=\"http:\/\/casperjs.org\/installation.html\">installation guide<\/a> and <a href=\"http:\/\/casperjs.org\/api.html#casper\">API<\/a><br \/>\n* <a href=\"https:\/\/nicolas.perriault.net\/code\/2012\/introducing-casperjs-toolkit-phantomjs\/\">Introductionary article<\/a> from CasperJS creator <strong>Nicolas Perriault<\/strong><br \/>\n* <a href=\"http:\/\/kvz.io\/blog\/2012\/11\/03\/highlevel-testing-with-casperjs\/\">Highlevel testing with CasperJS<\/a> by <strong>Kevin van Zonneveld<\/strong><br \/>\n* <a href=\"https:\/\/github.com\/robfletcher\/grails-angular-scaffolding\">grails-angular-scaffolding<\/a> plugin by <strong>Rob Fletcher<\/strong> with some working CasperJS <a href=\"https:\/\/github.com\/robfletcher\/grails-angular-scaffolding\/tree\/master\/test\/apps\/grails-ng\">tests<\/a><\/p>\n<h2 id=\"full-example\">Full example<\/h2>\n<p>I run my test suite via following script:<\/p>\n<div class=\"highlight\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">casperjs test --direct --log-level=debug --testhost=localhost:8080 --includes=test\/casper\/includes\/casper-angular.coffee,test\/casper\/includes\/pages.coffee test\/casper\/specs\/\r\n<\/pre>\n<\/div>\n<p>casper-angular.coffe<\/p>\n<div class=\"highlight\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">casper.test.on \"fail\", (failure) -&gt;\r\n    casper.capture(screenshot)\r\n\r\ntesthost   = casper.cli.get \"testhost\"\r\nscreenshot = 'test-fail.png'\r\n\r\ncasper\r\n    .log(\"Using testhost: #{testhost}\", \"info\")\r\n    .log(\"Using screenshot: #{screenshot}\", \"info\")\r\n\r\ncasper.waitUntilVisible = (selector, message, callback) -&gt;\r\n    @waitFor -&gt;\r\n        @visible selector\r\n    , callback, (timeout) -&gt;\r\n        @log(\"Selector [#{selector}] not visible, failing\")\r\n        withParentSelector selector, (parent) -&gt;\r\n            casper.log(\"Output of parent selector [#{parent}]\")\r\n            casper.debugHTML(parent)\r\n        @echo message, \"RED_BAR\"\r\n        @capture(screenshot)\r\n        @test.fail(f(\"Wait timeout occured (%dms)\", timeout))\r\n\r\nwithParentSelector = (selector, callback) -&gt;\r\n    if selector.lastIndexOf(\" \") &gt; 0\r\n       parent = selector[0..selector.lastIndexOf(\" \")-1]\r\n       callback(parent)\r\n<\/pre>\n<\/div>\n<p>Sample pages.coffee:<\/p>\n<div class=\"highlight\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">x = require('casper').selectXPath\r\n\r\nclass EditDocumentPage\r\n\r\n    assertAt: -&gt;\r\n        casper.test.assertSelectorExists(\"div.customerAccountInfo\", 'at EditDocumentPage')\r\n\r\n    templatesTreeFirstCategory: 'ul.tree li label'\r\n    templatesTreeFirstTemplate: 'ul.tree li a'\r\n    closePreview: '.closePreview a'\r\n    smallPreview: '.smallPreviewContent img'\r\n    bigPreview: 'img.previewImage'\r\n    confirmDelete: x(\"\/\/div[@class='modal-footer']\/a[1]\")\r\n\r\ncasper.editDocument = new EditDocumentPage()\r\n<\/pre>\n<\/div>\n<p>End a test script:<\/p>\n<div class=\"highlight\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">testhost = casper.cli.get \"testhost\" or 'localhost:8080'\r\n\r\ncasper.start \"http:\/\/#{testhost}\/app\", -&gt;\r\n    @test.assertHttpStatus 302\r\n    @test.assertUrlMatch \/\\\/fakeLogin\/, 'auto login'\r\n    @test.assert @visible('input#Create'), 'mock login button'\r\n    @click 'input#Create'\r\n\r\ncasper.then -&gt;\r\n    @test.assertUrlMatch \/document#\\\/edit\/, 'new document'\r\n    @editDocument.assertAt()\r\n    @waitUntilVisible @editDocument.templatesTreeFirstCategory, 'template categories not visible', -&gt;\r\n        @click @editDocument.templatesTreeFirstCategory\r\n        @waitUntilVisible @editDocument.templatesTreeFirstTemplate, 'template not visible', -&gt;\r\n            @click @editDocument.templatesTreeFirstTemplate\r\n\r\ncasper.then -&gt;\r\n    @waitUntilVisible @editDocument.smallPreview, 'small preview not visible', -&gt;\r\n        # could be dblclick \/ whatever\r\n        @mouseEvent('click', @editDocument.smallPreview)\r\n\r\ncasper.then -&gt;\r\n    @waitUntilVisible @editDocument.bigPreview, 'big preview should be visible', -&gt;\r\n        @test.assertEvalEquals -&gt;\r\n            $('.pageCounter').text()\r\n        , '1\/1', 'page counter should be visible'\r\n        @click @editDocument.closePreview\r\n\r\ncasper.then -&gt;\r\n    @click 'button.cancel'\r\n    @waitUntilVisible '.modal-footer', 'delete confirmation not visible', -&gt;\r\n        @click @editDocument.confirmDelete\r\n\r\ncasper.run -&gt;\r\n    @test.done()\r\n<\/pre>\n<\/div>\n<p>Here is a list of CasperJS features\/caveats used here:<\/p>\n<ul>\n<li>Using <a href=\"http:\/\/coffeescript.org\/\">CoffeeScript<\/a> is a huge win for your test code to look neat<\/li>\n<li>When using <a href=\"http:\/\/casperjs.org\/testing.html#casper-test-command\">casper test<\/a> command, beware of different (than above articles) logging setup. You can pass <code>--direct --log-level=debug<\/code> from commandline for best results. Logging is essential here since Phantom often exists without any error and you do want to know what just happened.<\/li>\n<li>Extract your helper code into separate files and include them by using <code>--includes<\/code> switch.<\/li>\n<li>When passing server URL as a commandline switch remember that in CoffeeScript variables are not visible between multiple source files (unless getting them via window object)<\/li>\n<li>It\u2019s good to override standard waitUntilVisible with capting a screenshot and making a proper <code>log<\/code> statement. In my version I also look for a parent selector and <code>debugHTML<\/code> the content of it &#8211; great for debugging what is actually rendered by the browser.<\/li>\n<li>Selenium and Geb have a nice concept of <a href=\"http:\/\/code.google.com\/p\/selenium\/wiki\/PageObjects\">Page Objects<\/a> &#8211; an abstract models of pages rendered by your application. Using CoffeeScript you can write your own classes, bind selectors to properties and use then in your code script. Assigning the objects to casper instance will end up with quite nice syntax like <code>@editDocument.assertAt()<\/code>.<\/li>\n<li>There is some issue with CSS <code>:first<\/code> and <code>:last<\/code> selectors. I cannot get them working (but maybe I\u2019m doing something wrong?). But in CasperJS you can also use XPath selectors which are fine for matching n-th child of some element (<code>x(\"\/\/div[@class='modal-footer']\/a[1]\")<\/code>).\n<p><strong>Update<\/strong>: <code>:first<\/code> and <code>:last<\/code> are not CSS3 selectors, but JQuery ones. <a href=\"http:\/\/www.w3.org\/TR\/selectors\/#selectors\">Here<\/a> is a list of CSS3 selectors, all of these are supported by CasperJS. So you can use <code>nth-child(1)<\/code> is this case. Thanks Andy and Nicolas for the comments!<\/li>\n<\/ul>\n<p>Working with CasperJS can lead you to a few hour stall, but after getting things working you have a new, cool tool in your box!<\/p>\n","protected":false},"excerpt":{"rendered":"Why CasperJS\nBeing a Java developer is kinda hard these days. Java may not be dead yet, but when keeping in sync with all the hipster JavaScript frameworks could make us feel a bit outside the playground. It&rsquo;s even hard to list JavaScript frameworks with latest releases on one website.\nIn my current project, we are using AngularJS. It&rsquo;a a nice abstraction of MV* pattern in frontend layer of any web application (we use Grails underneath). Here is a nice article with an 8-point Win List of Angular way of handling AJAX calls and updating the view. So it&rsquo;s not only a funny new framework but a truly helper of keeping your code clean and neat.\nBut there is also another area when you can put helpful JS framework in place of plan-old-java one &#8211; functional tests. Especially when you are dealing with one page app with lots of asynchronous REST\/JSON communication. \nSelenium and Geb\nIn Java\/JVM project the typical is to use Selenium with some wrapper like Geb. So you start your project, setup your CI-functional testing pipeline and&hellip; after 1 month of coding your tests stop working and being maintainable. The frameworks itselves are not bad, but the typical setup is so heavy and has so many points of failure that keeping it working in a real life project is really hard.\nHere is my list of common myths about Selenium:\n* It allows you to record test scripts via handy GUI &#8211; maybe some static request\/response sites. In modern web applications with asynchronous REST\/JSON communication your tests must contain a lot of &ldquo;waitFor&rdquo; statements and you cannot automate where these should be included.\n* It allows you to test your web app against many browsers &#8211; don&rsquo;t try to automate IE tests! You have to manually open your app in IE to see how it actually bahaves!\n* It integrates well with continuous integration servers like Jenkins &#8211; you have to setup Selenium Grid on server with X installed to run tests on Chrome or Firefox and a Windows server for IE. And the headless HtmlUnit driver lacks a lot of JS support.\nSo I decided to try something different and introduce a bit of JavaScript tooling in our project by using CasperJS.\nIntroduction\nCasperJS is simple but powerful navigation scripting &amp; testing utility for PhantomJS &#8211; scritable headless WebKit (which is an rendering engine used by Safari and Chrome). In short &#8211; CasperJS allows you to navigate and make assertions about web pages as they&rsquo;d been rendered in Google Chrome. It is enough for me to automate the functional tests of my application.\nIf you want a gentle introduction to the world of CasperJS I suggest you to read:\n* Official website, especially installation guide and API\n* Introductionary article from CasperJS creator Nicolas Perriault\n* Highlevel testing with CasperJS by Kevin van Zonneveld\n* grails-angular-scaffolding plugin by Rob Fletcher with some working CasperJS tests\nFull example\nI run my test suite via following script:\n\ncasperjs test --direct --log-level=debug --testhost=localhost:8080 --includes=test\/casper\/includes\/casper-angular.coffee,test\/casper\/includes\/pages.coffee test\/casper\/specs\/\r\n\n\ncasper-angular.coffe\n\ncasper.test.on \"fail\", (failure) -&gt;\r\n    casper.capture(screenshot)\r\n\r\ntesthost   = casper.cli.get \"testhost\"\r\nscreenshot = 'test-fail.png'\r\n\r\ncasper\r\n    .log(\"Using testhost: #{testhost}\", \"info\")\r\n    .log(\"Using screenshot: #{screenshot}\", \"info\")\r\n\r\ncasper.waitUntilVisible = (selector, message, callback) -&gt;\r\n    @waitFor -&gt;\r\n        @visible selector\r\n    , callback, (timeout) -&gt;\r\n        @log(\"Selector [#{selector}] not visible, failing\")\r\n        withParentSelector selector, (parent) -&gt;\r\n            casper.log(\"Output of parent selector [#{parent}]\")\r\n            casper.debugHTML(parent)\r\n        @echo message, \"RED_BAR\"\r\n        @capture(screenshot)\r\n        @test.fail(f(\"Wait timeout occured (%dms)\", timeout))\r\n\r\nwithParentSelector = (selector, callback) -&gt;\r\n    if selector.lastIndexOf(\" \") &gt; 0\r\n       parent = selector[0..selector.lastIndexOf(\" \")-1]\r\n       callback(parent)\r\n\n\nSample pages.coffee:\n\nx = require('casper').selectXPath\r\n\r\nclass EditDocumentPage\r\n\r\n    assertAt: -&gt;\r\n        casper.test.assertSelectorExists(\"div.customerAccountInfo\", 'at EditDocumentPage')\r\n\r\n    templatesTreeFirstCategory: 'ul.tree li label'\r\n    templatesTreeFirstTemplate: 'ul.tree li a'\r\n    closePreview: '.closePreview a'\r\n    smallPreview: '.smallPreviewContent img'\r\n    bigPreview: 'img.previewImage'\r\n    confirmDelete: x(\"\/\/div[@class='modal-footer']\/a[1]\")\r\n\r\ncasper.editDocument = new EditDocumentPage()\r\n\n\nEnd a test script:\n\ntesthost = casper.cli.get \"testhost\" or 'localhost:8080'\r\n\r\ncasper.start \"http:\/\/#{testhost}\/app\", -&gt;\r\n    @test.assertHttpStatus 302\r\n    @test.assertUrlMatch \/\\\/fakeLogin\/, 'auto login'\r\n    @test.assert @visible('input#Create'), 'mock login button'\r\n    @click 'input#Create'\r\n\r\ncasper.then -&gt;\r\n    @test.assertUrlMatch \/document#\\\/edit\/, 'new document'\r\n    @editDocument.assertAt()\r\n    @waitUntilVisible @editDocument.templatesTreeFirstCategory, 'template categories not visible', -&gt;\r\n        @click @editDocument.templatesTreeFirstCategory\r\n        @waitUntilVisible @editDocument.templatesTreeFirstTemplate, 'template not visible', -&gt;\r\n            @click @editDocument.templatesTreeFirstTemplate\r\n\r\ncasper.then -&gt;\r\n    @waitUntilVisible @editDocument.smallPreview, 'small preview not visible', -&gt;\r\n        # could be dblclick \/ whatever\r\n        @mouseEvent('click', @editDocument.smallPreview)\r\n\r\ncasper.then -&gt;\r\n    @waitUntilVisible @editDocument.bigPreview, 'big preview should be visible', -&gt;\r\n        @test.assertEvalEquals -&gt;\r\n            $('.pageCounter').text()\r\n        , '1\/1', 'page counter should be visible'\r\n        @click @editDocument.closePreview\r\n\r\ncasper.then -&gt;\r\n    @click 'button.cancel'\r\n    @waitUntilVisible '.modal-footer', 'delete confirmation not visible', -&gt;\r\n        @click @editDocument.confirmDelete\r\n\r\ncasper.run -&gt;\r\n    @test.done()\r\n\n\nHere is a list of CasperJS features\/caveats used here:\n\nUsing CoffeeScript is a huge win for your test code to look neat\nWhen using casper test command, beware of different (than above articles) logging setup. You can pass --direct --log-level=debug from commandline for best results. Logging is essential here since Phantom often exists without any error and you do want to know what just happened.\nExtract your helper code into separate files and include them by using --includes switch.\nWhen passing server URL as a commandline switch remember that in CoffeeScript variables are not visible between multiple source files (unless getting them via window object)\nIt&rsquo;s good to override standard waitUntilVisible with capting a screenshot and making a proper log statement. In my version I also look for a parent selector and debugHTML the content of it &#8211; great for debugging what is actually rendered by the browser.\nSelenium and Geb have a nice concept of Page Objects &#8211; an abstract models of pages rendered by your application. Using CoffeeScript you can write your own classes, bind selectors to properties and use then in your code script. Assigning the objects to casper instance will end up with quite nice syntax like @editDocument.assertAt().\nThere is some issue with CSS :first and :last selectors. I cannot get them working (but maybe I&rsquo;m doing something wrong?). But in CasperJS you can also use XPath selectors which are fine for matching n-th child of some element (x(\"\/\/div[@class='modal-footer']\/a[1]\")).\nUpdate: :first and :last are not CSS3 selectors, but JQuery ones. Here is a list of CSS3 selectors, all of these are supported by CasperJS. So you can use nth-child(1) is this case. Thanks Andy and Nicolas for the comments!\n\nWorking with CasperJS can lead you to a few hour stall, but after getting things working you have a new, cool tool in your box!\n","protected":false},"author":5,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11],"tags":[],"class_list":{"0":"post-10953","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-development-design"},"_links":{"self":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/10953","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/comments?post=10953"}],"version-history":[{"count":10,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/10953\/revisions"}],"predecessor-version":[{"id":14827,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/10953\/revisions\/14827"}],"wp:attachment":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/media?parent=10953"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/categories?post=10953"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/tags?post=10953"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}