Testing React Apps with Phantom/Casper

只愿长相守 提交于 2019-12-08 04:42:47

问题


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"

回答1:


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.




回答2:


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
            });
    });
});


来源:https://stackoverflow.com/questions/35353482/testing-react-apps-with-phantom-casper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!