如何对 JavaScript 响应执行功能测试?
我注意到,在 Rails 中,为 js 请求渲染回文本,并将文本嵌入到 jquery 方法调用中以将其插入到 DOM 中是很常见的。
// javascript code
$.getScript("/some_url");
// rails partial code, to make things more clear I have added some simple html
$("#some_id").text(unescape_javascript('<div id="foo">bar</div>'))
我的问题是如何在对这样的响应文本进行功能测试时执行assert_select 或等效操作?
//
class FooBarControllerTest < ...
test "javascript response" do
xhr :get, :new
// how could I test the div here
assert_select "#foo", "bar" // this doesn't work
end
end
** 更新了代码以使其更加清晰
I noticed that it is quite common in Rails to render back text for js requests with the text embedded within a jquery method call to insert it into the DOM.
// javascript code
$.getScript("/some_url");
// rails partial code, to make things more clear I have added some simple html
$("#some_id").text(unescape_javascript('<div id="foo">bar</div>'))
My question is how do you perform assert_select, or the equivalent, within a functional test on response text like this?
//
class FooBarControllerTest < ...
test "javascript response" do
xhr :get, :new
// how could I test the div here
assert_select "#foo", "bar" // this doesn't work
end
end
** Updated code to make this more clear
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
经过一番摆弄后,这对我有用。最棘手的部分是在创建 HTML::Document 对象之前清理所有分隔字符,例如 \t、\n 和 \。
After some fiddling around this works for me. The trickiest part is cleaning up all of the delimited chars such as \t,\n and \ before creating the HTML::Document object.
我不知道你会如何从rails请求它,但是使用ajax和jquery会像这样:
你需要的是eval,所以只需将你的字符串放在eval()内部作为javascript运行;
i dont know how would you request it from rails but with ajax and jquery would go like this:
thing you need is eval, so just put your string that hawe to be runed as javascript inside of eval();
对于 Rails 4.x,这对我有用(技巧是在规范/测试期间覆盖“document_root_element”方法):
With Rails 4.x, this works for me (the trick is to override the "document_root_element" method during the spec/test):