PhantomJS
O fantasminha camarada




       Henrique Gogó
       @henriquegogo
O que é PhantomJS?

   Um "browser" webkit com API JavaScript
       completa que roda no console.

Suporte nativo a vários padrões web standards:
 DOM, seletores CSS, JSON, Ajax, Canvas e
                     SVG.
Para que serve?
  Rodar testes funcionais (de JavaScript) com
frameworks como Jasmine, QUnit ou CasperJS.

  Acessar e manipular páginas com acesso
 completo ao DOM e bibliotecas de JS como
                 jQuery.
Por que não WebRat?

    WebRat é um simulador de browser com
 capacidade de DOM, seletores CSS, de fácil
integração com RSpec, Cucumber, Test::Unit e
                   outros.

            Mas e o JavaScript?
Por que não Selenium?

 Selenium é contém uma API para você realizar
testes de aceitação em diversos browsers. Para
   isso ele levanta uma instância do browser.
Usando PhantomJS como
    engine JavaScript do Capybara

  https://github.com/jonleighton/poltergeist


require 'capybara/poltergeist'
Capybara.javascript_driver = :poltergeist
Ou simplesmente QUnit

$ phantomjs run-qunit.js test/index.html


Tests completed in 1528 milliseconds.
1223 tests of 1223 passed, 0 failed.
QUnit


test("a basic test example", function() {
  ok( true, "this test is fine" );
  var value = "hello";
  equal( value, "hello", "We expect value to be
hello" );
});
Exemplos
//teste.js
var page = new WebPage();
var url = "http://www.gogs.com.br/";
page.open(url, function (status) {
    //Página carregada
    phantom.exit();
});

$ phantomjs teste.js
Manipulação de DOM
var page = new WebPage();
console.log('Seu user agent é:' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent';
page.open('http://www.httpuseragent.org', function (status) {
    if (status !== 'success') {
        console.log('Unable to access network');
    } else {
        var ua = page.evaluate(function () {
            return document.getElementById('myagent').innerText;
        });
        console.log(ua);
    }
    phantom.exit();
});
Listener de requisições
var url = phantom.args[0];

var page = new WebPage();
page.onResourceRequested = function (request) {
   console.log('Request ' + JSON.stringify(request,
undefined, 4));
};
page.onResourceReceived = function (response) {
   console.log('Receive ' + JSON.stringify(response,
undefined, 4));
};
page.open(url);
page.render()
$ phantomjs rasterize.js http://www.google.com.br google.png
Blá   Blá   Blá!
Blá   Blá   Blá!
Blá   Blá   Blá!
Blá   Blá   Blá!
Blá   Blá   Blá!
Então...

Quer fazer testes de aceitação com fidelidade à
   engine WebKit (Chrome, Safari, Mobile
                  browsers)?

   Quer testar JavaScript sem precisar abrir
                  browser?

 Quer integrar com Ruby usando Capybara, ou
outras plataformas como C# (usando Chutzpah)?
PhantomJS
Perguntas?



              @henriquegogo

             www.gogs.com.br

PhantomJS - O Fantasminha Camarada

  • 1.
    PhantomJS O fantasminha camarada Henrique Gogó @henriquegogo
  • 2.
    O que éPhantomJS? Um "browser" webkit com API JavaScript completa que roda no console. Suporte nativo a vários padrões web standards: DOM, seletores CSS, JSON, Ajax, Canvas e SVG.
  • 3.
    Para que serve? Rodar testes funcionais (de JavaScript) com frameworks como Jasmine, QUnit ou CasperJS. Acessar e manipular páginas com acesso completo ao DOM e bibliotecas de JS como jQuery.
  • 4.
    Por que nãoWebRat? WebRat é um simulador de browser com capacidade de DOM, seletores CSS, de fácil integração com RSpec, Cucumber, Test::Unit e outros. Mas e o JavaScript?
  • 5.
    Por que nãoSelenium? Selenium é contém uma API para você realizar testes de aceitação em diversos browsers. Para isso ele levanta uma instância do browser.
  • 6.
    Usando PhantomJS como engine JavaScript do Capybara https://github.com/jonleighton/poltergeist require 'capybara/poltergeist' Capybara.javascript_driver = :poltergeist
  • 7.
    Ou simplesmente QUnit $phantomjs run-qunit.js test/index.html Tests completed in 1528 milliseconds. 1223 tests of 1223 passed, 0 failed.
  • 8.
    QUnit test("a basic testexample", function() { ok( true, "this test is fine" ); var value = "hello"; equal( value, "hello", "We expect value to be hello" ); });
  • 9.
    Exemplos //teste.js var page =new WebPage(); var url = "http://www.gogs.com.br/"; page.open(url, function (status) { //Página carregada phantom.exit(); }); $ phantomjs teste.js
  • 10.
    Manipulação de DOM varpage = new WebPage(); console.log('Seu user agent é:' + page.settings.userAgent); page.settings.userAgent = 'SpecialAgent'; page.open('http://www.httpuseragent.org', function (status) { if (status !== 'success') { console.log('Unable to access network'); } else { var ua = page.evaluate(function () { return document.getElementById('myagent').innerText; }); console.log(ua); } phantom.exit(); });
  • 11.
    Listener de requisições varurl = phantom.args[0]; var page = new WebPage(); page.onResourceRequested = function (request) { console.log('Request ' + JSON.stringify(request, undefined, 4)); }; page.onResourceReceived = function (response) { console.log('Receive ' + JSON.stringify(response, undefined, 4)); }; page.open(url);
  • 12.
    page.render() $ phantomjs rasterize.jshttp://www.google.com.br google.png
  • 13.
    Blá Blá Blá! Blá Blá Blá! Blá Blá Blá! Blá Blá Blá! Blá Blá Blá!
  • 14.
    Então... Quer fazer testesde aceitação com fidelidade à engine WebKit (Chrome, Safari, Mobile browsers)? Quer testar JavaScript sem precisar abrir browser? Quer integrar com Ruby usando Capybara, ou outras plataformas como C# (usando Chutzpah)?
  • 15.
  • 17.
    Perguntas? @henriquegogo www.gogs.com.br