为什么我的单元测试中的 UIWebView 为空?

发布于 2024-12-02 09:36:09 字数 1238 浏览 1 评论 0原文

我将应用生成的内容放入 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

静谧 2024-12-09 09:36:09

UIWebView 渲染需要很长时间,因此问题可能是您在内容完全加载之前访问内容。

挂钩 UIWebViewDelegatewebViewDidFinishLoad: 方法以确保内容已准备就绪。

更新:
也许 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's webViewDidFinishLoad: method to make sure the content is ready.

Update:
Maybe WebViewJavascriptBridge will bring some help.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文