Espresso:如何在WebView上调用evaluateJavascript()

San*_* Kh 3 android android-espresso

我试图获得一个实例WebView,以便我可以调用evaluateJavascript()它.我编写了一个自定义匹配器,然后尝试将其分配WebView给静态变量,如下所示:

 public static WebView view1;

 public static Matcher<View> isJavascriptEnabled1() {
    return new BoundedMatcher<View, WebView>(WebView.class) {
        @Override
        public void describeTo(Description description) {
            description.appendText("WebView with JS enabled");
        }
        @Override
        public boolean matchesSafely(WebView webView) {
            view1 =webView;
            return webView.getSettings().getJavaScriptEnabled();
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

在我的测试课中,我打电话给:

 CustomMatcher.isJavascriptEnabled1();
 CustomMatcher.view1.evaluateJavascript("$('.status dl       dd').get(0).innerText.replace('pts.', '').replace(',', '').trim()\"]",new    ValueCallback<String>() {
   @Override
   public void onReceiveValue(String s) {
       Log.d("LogName", s); // Prints asd
   }
Run Code Online (Sandbox Code Playgroud)

});

我收到错误: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.webkit.WebView.evaluateJavascript(java.lang.String, android.webkit.ValueCallback)' on a null object reference

tha*_*sma 5

您没有使用它Matcher来匹配视图.它不起作用,因为调用isJavascriptEnabled1()只是创建一个新的自定义实例Matcher.但是,如matchesSafely()永远不会执行,这就是为什么CustomMatcher.view1null.要使代码正常工作,您必须与您的代码Espresso.onView()一起使用Matcher:

 // Use onView and the matcher to find a web view with enabled java script
 Espresso.onView(CustomMatcher.isJavascriptEnabled1());

 // Now CustomMatcher.view1 should not be null (if there is a web view)
 CustomMatcher.view1.evaluateJavascript("$('.status dl       dd').get(0).innerText.replace('pts.', '').replace(',', '').trim()\"]",new    ValueCallback<String>() {
   @Override
   public void onReceiveValue(String s) {
       Log.d("LogName", s); // Prints asd
   }
});
Run Code Online (Sandbox Code Playgroud)

但那仍然不正确.该方法evaluateJavascript()是异步的,Espresso不会等待调用callback(onReceiveValue()).所以测试很可能在onReceive()调用之前完成.

还有Espresso Web用于测试WebViews.根据您的目标,您可能会发现它很有用.Espresso Web也在底层执行java脚本.

如果不使用Espresso Web,我建议编写一个自定义的ViewAction,将在匹配的上执行WebView.此操作可以使用WebView来评估java脚本:

/**
 * {@link ViewAction} that evaluates javascript in a {@link WebView}.
 */
public class EvaluateJsAction implements ViewAction, ValueCallback<String> {

    private static final long TIME_OUT = 5000;
    private final String mJsString;
    private final AtomicBoolean mEvaluateFinished = new AtomicBoolean(false);

    public EvaluateJsAction(final String javaScriptString) {
        mJsString = javaScriptString;
    }

    @Override
    public Matcher<View> getConstraints() {
        return isAssignableFrom(WebView.class);
    }

    @Override
    public String getDescription() {
        return "evaluate '" + mJsString + "' on webview";
    }

    @Override
    public void perform(UiController uiController, View view) {
        uiController.loopMainThreadUntilIdle();

        final WebView webView = (WebView) view;
        webView.evaluateJavascript(mJsString, this);

        final long timeOut = System.currentTimeMillis() + TIME_OUT;
        while (!mEvaluateFinished.get()) {
            if (timeOut < System.currentTimeMillis()) {
                throw new PerformException.Builder()
                        .withActionDescription(this.getDescription())
                        .withViewDescription(HumanReadables.describe(view))
                        .withCause(new RuntimeException(String.format(Locale.US,
                                "Evaluating java script did not finish after %d ms of waiting.", TIME_OUT)))
                        .build();
            }
            uiController.loopMainThreadForAtLeast(50);
        }
    }

    @Override
    public void onReceiveValue(String value) {
        mEvaluateFinished.set(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用此操作:

onView(withJavaScriptEnabled()).perform(new EvaluateJsAction(theJavaScriptString));
Run Code Online (Sandbox Code Playgroud)