Brett DeWoody
Brett DeWoody

Reputation: 62773

Testing React Apps with Phantom/Casper

I'm diving into functional testing and attempting to get a few simple tasks working. The app is built in ReactJS and I've decided to use Phantom/Casper. The problem is that even the most basic tasks fail.

In short, is there a trick for testing React apps with Phantom/Casper?

I've installed Phantom (v.2.1.1) and Casper (v1.1.0-beta5). As a first attempt I created a simple script to capture an image:

capture.js

var casper = require('casper').create({
  viewportSize: {
    width: 1024,
    height: 768
  },
  verbose: true,
  logLevel: "debug"
});

casper.start('http://localhost:9494', function() {
  console.log("page loaded");
});

casper.then(function() {
    this.capture('img.png');
  });
});

casper.run();

Then run the script:

> casperjs capture.js

Viewing localhost:9494 in my browser pulls up the app as it should. But the resulting capture() image is a blank screen.

I've also tried adding a wait(), waitForSelector() and waitForResource() to no avail.

Here's the output in the console:

[info] [phantom] Starting...
[info] [phantom] Running suite: 2 steps
[debug] [phantom] opening url: http://localhost:9494/, HTTP GET
[debug] [phantom] Navigation requested: url=http://localhost:9494/, type=Other, willNavigate=true, isMainFrame=true
[debug] [phantom] url changed to "http://localhost:9494/"
[debug] [phantom] Successfully injected Casper client-side utilities
[info] [phantom] Step anonymous 2/2 http://localhost:9494/ (HTTP 200) page loaded
[debug] [phantom] Capturing page to /path/to/img.png
[info] [phantom] Capture saved to /path/to/img.png
[info] [phantom] Step anonymous 2/2: done in 848ms.
[info] [phantom] Done 2 steps in 848ms
[debug] [phantom] Navigation requested: url=about:blank, type=Other, willNavigate=true, isMainFrame=true
[debug] [phantom] url changed to "about:blank"

Upvotes: 1

Views: 1693

Answers (2)

jpshook
jpshook

Reputation: 4944

You need to add the babel-polyfill NPM package to your project (or any other version of the polyfill) and then in your main index.js(x) entry point for your app, include this line at the top:

import 'babel-polyfill';

We were having the exact same issue you are experiencing and this fixed it for us.
We had tried injecting the babel polyfill as part of the Casper test suite, but it was not working.

Upvotes: 3

takacsmark
takacsmark

Reputation: 4441

Not sure how you did the waiting. Make sure your capture is in the wait callback. I usually use code like this and it often happens that you need to adjust the waiting time to see results.

3 seconds is usually enough to crawl public websites, that's how I use it.

casper.then(function() {
    this.wait(3000, function() {
        this.capture('foo.jpg', undefined, 
            {
                format: 'jpg',
                quality: 75
            });
    });
});

Upvotes: 1

Related Questions