A rough guide to testing your React-Native WebViews with Detox

A rough guide to testing your React-Native WebViews with Detox

… well, on Android anyway.

·

3 min read

You can finally write end-to-end tests for your WebViews using Detox!

… well, on Android anyway.

At this moment, iOS is not supported. However, that's likely to change in future. Interestingly, although functionality exists for testing on android, Detox's docs haven't been officially updated to include webview testing. This suggests the work might be ongoing and fairly hush hush. Regardless, being able to test webviews on android remains a giant leap for developer-kind!


How to add a WebView to your app

To include a WebView, add the react-native-webview package as a dependency to your package.json. Import the WebView component, and pass it a source as shown below. Make sure to include a testID to your WebView so it can be found by detox when you run your test.

How to write a test for the webview

For this example, we are using the Twitter Login page. We would like to allow the user to:

  • Enter a username
  • Enter a password
  • And click the Login button

We first define a sleep function. Sometimes, it takes a while for a webview to load, so it might be useful to add a delay to ensure it finishes loading before running the tests.

As seen below, we can use Detox's web object to interact with the view and make assertions on located elements.

Locating DOM elements:

Detox's web builds on Android's Expresso-Web and provides a list of functions for selecting DOM elements.

  • id -  finds an element on the DOM tree by its id
  • text - finds an element on the DOM tree by its CSS class
  • cssSelector - finds an element on the DOM tree matching the given CSS selector
  • name - finds an element on the DOM tree by its "name" attribute
  • xpath - finds an element on the DOM tree by its XPath
  • href - finds an <a> element on the DOM tree by its link text
  • hrefContent - finds an <a> element on the DOM tree by its partial link text
  • tag - finds an element on the DOM tree by its tag name

Interacting with located elements:

After locating your element, you can simulate user interaction with the following self-explanatory methods:

  • tap
  • typeText
  • getText
  • clearText
  • replaceText
  • scrollToView
  • getCurrentUrl
  • getTitle
  • runScript
  • runScriptWithArgs

Using Matchers

Detox web also comes with a fun set of matchers:

  • toExist()
  • toNotExist()
  • toHaveText()
  • toNotHaveText()

Although it might not seem like much, considering how integral webviews are to a lot of applications, this is truly a breakthrough for cross-platform mobile testing. I'm excited to see what this means for the future of mobile e2e testing.

The possibilities are endless!