如何对JavaScript响应执行function测试?

我注意到在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('
bar
'))

我的问题是你如何在这样的响应文本的function测试中执行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 

**更新了代码,使其更加清晰

我不知道你会如何从rails请求它,但是使用ajax和jquery会是这样的:

 $.ajax({ type: 'POST', url: 'getstring.php', data: '', success: function(server_response){ if(server_response){ eval(server_response); } else{ } } }); 

你需要的是eval ,所以只需把你的字符串作为jval(eval()中的javascript;

使用Rails 4.x,这对我有用(诀窍是在规范/测试期间覆盖“document_root_element”方法):

 context "with assert_select" do def document_root_element Nokogiri::HTML::Document.parse(@html).root end it "works" do xhr :get, :new @html = response.body # or wherever the response HTML comes from assert_select "#foo", "bar" # should work now end end