CasperJS HTTP身份验证

时间:2013-08-19 13:57:02

标签: testing phantomjs casperjs

无法简单地处理HTTP身份验证。这是我的代码:

var x = require('casper').selectXPath;
var casper = require('casper').create({
    verbose: false,
    logLevel: 'debug'
});
casper.options.viewportSize = {width: 1366, height: 667};
casper.start('https://example.com/a/dashboard');
casper.setHttpAuth('username', 'password');

casper.then(function() {
    this.test.assertUrlMatch(/^https:\/\/example.com\/a\/dashboard$/);
});

casper.run(function() {this.test.renderResults(true);});

我在控制台中看到的错误:

casperjs mytest.js
FAIL Current url matches the provided pattern
#    type: assertUrlMatch
#    subject: false
#    currentUrl: "https://example.com/login"
#    pattern: "/^https:\\/\\/example.com\\/a\\/dashboard$/"
FAIL 1 tests executed in 2.428s, 0 passed, 1 failed.

问:为什么我当前的Url与模式不匹配? 谢谢。

1 个答案:

答案 0 :(得分:9)

我认为您需要在加载页面之前致电casper.setHttpAuth()

您似乎忘记在casper.exit()结束时致电casper.run()

var x = require('casper').selectXPath;
var casper = require('casper').create({
    verbose: false,
    logLevel: 'debug'
});
casper.options.viewportSize = {width: 1366, height: 667};

casper.start();
casper.setHttpAuth('here_i_type_username', 'here_password');

casper.thenOpen('https://mysite.com/a/dashboard', function() {
    this.test.assertUrlMatch(/^https:\/\/mysite.com\/a\/dashboard$/);
});

casper.run(function() {
    this.test.renderResults(true);
    this.exit();
});