问题
It can be done with pure phantomjs like this:
var page = require('webpage').create();
var address = 'http://google.com/';
page.open(address, function(status) {
if (status !== 'success') {
console.log('FAIL to load the address');
} else {
console.log('SUCCESS');
}
phantom.exit();
});
but I'd like it to support casperjs test
command. The best I came up with is:
casper.test.begin("Hello, Test!", 1, function(test) {
var page = require('webpage').create();
var address = 'http://google_doesnotexist.com/';
page.open(address, function(status) {
test.assert(status == 'success');
//phantom.exit();
test.done();
});
});
it works fine if page really opens, but the script does not stop at all if the page does not open.
回答1:
Apart from your own answer, you can explicitly check the status through the status function:
casper.start("http://www.example.com/", function() {
test.assert(this.status().currentHTTPStatus == 200);
});
or even easier by using the tester module as you already do this:
casper.start("http://www.example.com/", function() {
test.assertHttpStatus(200);
});
回答2:
There is no example with function argument in casperjs docs, but I've guessed it right:)
casper.test.begin('Page opens fine', 1, function suite(test) {
casper.start("http://www.google_nononon.com/", function(result) {
//console.log(status);
//require('utils').dump(status);
test.assert(result.status == 200);
});
casper.run(function() {
test.done();
});
});
来源:https://stackoverflow.com/questions/24818166/casperjs-test-if-page-opens