为什么我的单元测试中的 UIWebView 为空?
我将应用生成的内容放入 UIWebView
中,并尝试测试我是否正确执行此操作。这是我要放入 Web 视图中的 HTML 字符串:
@"<html><head></head><body><p>Come, let me clutch thee. I have thee not, and yet I see thee still. Art thou not, fatal vision, sensible to feeling as to sight?</p></body></html>"
它会这样进入 Web 视图:
[self.webView loadHTMLString: [self HTMLStringForSnippet: model.body] baseURL: nil];
其中 model.body
仅包含
元素,并且
-HTMLStringForSnippet:
将其包装为格式良好的 HTML。在我的测试中,我依靠这个问题的答案来检索 HTML通过 JavaScript 获取正文内容:
- (void)testCorrectHTMLLoadedInWebView {
UIWebView *bodyView = controller.webView;
NSString *bodyHTML = [bodyView stringByEvaluatingJavaScriptFromString: @"document.body.innerHTML"];
STAssertEqualObjects(bodyHTML, model.body, @"Model body should be used for the web view content");
}
虽然我可以通过单步执行代码看到 UIWebView
已正确创建,并在 -loadHTMLString:baseURL:
中传递了正确的 HTML,但测试bodyHTML
为空。那么我该怎么做才能看到我期望的和之前传递到 Web 视图的实际内容呢?
I'm putting app-generated content into a UIWebView
, and trying to test that I'm doing it correctly. Here's the HTML string I'm putting into the web view:
@"<html><head></head><body><p>Come, let me clutch thee. I have thee not, and yet I see thee still. Art thou not, fatal vision, sensible to feeling as to sight?</p></body></html>"
And it gets into the web view thus:
[self.webView loadHTMLString: [self HTMLStringForSnippet: model.body] baseURL: nil];
where model.body
contains just the <p/>
element, and -HTMLStringForSnippet:
wraps it into well-formed HTML. In my test, I rely on the answers to this question to retrieve the HTML content of the body via JavaScript:
- (void)testCorrectHTMLLoadedInWebView {
UIWebView *bodyView = controller.webView;
NSString *bodyHTML = [bodyView stringByEvaluatingJavaScriptFromString: @"document.body.innerHTML"];
STAssertEqualObjects(bodyHTML, model.body, @"Model body should be used for the web view content");
}
While I can see by stepping through the code that the UIWebView
is created correctly and is passed the correct HTML in -loadHTMLString:baseURL:
, in the test bodyHTML
is empty. So what do I have to do to see the actual content I expect and previously passed to the web view?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
UIWebView
渲染需要很长时间,因此问题可能是您在内容完全加载之前访问内容。挂钩
UIWebViewDelegate
的webViewDidFinishLoad:
方法以确保内容已准备就绪。更新:
也许 WebViewJavascriptBridge 会带来一些帮助。
It takes a noticeable time for the
UIWebView
to render therefore the problem may be that you access the content before it is fully loaded.Hook on
UIWebViewDelegate
'swebViewDidFinishLoad:
method to make sure the content is ready.Update:
Maybe WebViewJavascriptBridge will bring some help.