【问题标题】:nodejs casperjs ejs express: settings values not seen by casperjsnodejs casperjs ejs express:casperjs看不到的设置值
【发布时间】:2013-04-22 10:03:35
【问题描述】:

CasperJS 似乎无法看到从 express 通过 app.settings 传递的值。有什么我遗漏的吗?

提前感谢任何可以为我指出解决方案的人!

这是一个 hello world 节点服务器:

hello.js
var http = require('http'),
    express = require('express'),
    app = express();

app.configure(function()
{
    app.set('view engine', 'ejs');
    app.set('views', __dirname);
    app.set('message', 'hello world!');
    app.set('secretmessage', 'foobar');

    app.get("/", function(req, res)
    {
        res.render('index.ejs', { layout:false });
    });
});

http.createServer(app).listen(3000, function(){
  console.log("Express server listening on port 3000");
});

在同一个文件夹中:

index.ejs
<!DOCTYPE html>
<html>
   <body>
      <input type="hidden" id="secret" value="<%= settings.secretmessage %>">
      <p><%= settings.message %></p>
   </body>
</html>

当我以node hello.js 开头时,它会恰当地告诉我服务器正在监听:

Express server listening on port 3000

这是返回的 html,如 Firefox 所见 - 正如您所期望的那样:

<!DOCTYPE html>
<html>
   <body>
      <input type="hidden" id="secret" value="foobar">
      <p>hello world!</p>
   </body>
</html>

我正在尝试使用 casperjs 对此进行测试。这是我的测试代码:

indextest.js
var casper = require('casper').create();

casper.start( 'http://localhost:3000', function start()
{
    var secretExists = this.evaluate( function() { return __utils__.exists( '#secret' ) });
    var secretValue = this.evaluate( function() { return __utils__.getFieldValue( 'secret' ) });
    casper.test.comment( 'Confirming hidden field secret exists and has value' );
    casper.test.assert( secretExists, 'secret exists' );
    casper.test.assertTruthy( secretValue, 'secret has value' );
});

casper.run(function run() {
    casper.test.done();
});

结果如下:

$ casperjs indextest.js
# Confirming hidden field secret exists and has value
PASS secret exists
FAIL secret has value
#    type: assertTruthy
#    subject: ""

不是将secret 的值视为“foobar”,而是将其视为“”。

【问题讨论】:

  • 有人向我指出了一个小语法错误,我已在上面的 casperjs 代码中更正了该错误。结果证明是一样的。

标签: node.js express phantomjs ejs casperjs


【解决方案1】:

事实证明,__utils__.exists() 使用 CSS 选择器,__utils__.getFieldValue() 使用 'name' 属性。

在 index.ejs 中添加 name="secret" 属性:

&lt;input type="hidden" id="secret" name="secret" value="&lt;%= settings.secretmessage %&gt;"

使两个测试都通过。感谢 V.P.寻求解决方案!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    相关资源
    最近更新 更多