Testing Vaadin Applications in the Browser With End-To-End Tests

End-to-end (e2e) tests are used to test the entire application. They’re far more coarse-grained than unit or integration tests. This makes them well suited to checking that the application works as a whole, and catching any regressions that may be missed by more specific tests.

End-to-end tests are executed in a browser window, controlled by a web driver and run on the server where the application is deployed. Vaadin TestBench takes care of these.

Note
Vaadin TestBench is a commercial product

The end-to-end tests use Vaadin TestBench, which is a commercial tool that is a part of the Vaadin Pro Subscription. You can get a free trial at https://vaadin.com/trial. All Vaadin Pro tools and components are free for students through the GitHub Student Developer Pack.

Creating the Base Test Class

To avoid repetition in each test class, it is a good idea to put common logic in an abstract class and have all tests extend this class. Most of the heavy lifting about starting browsers, etc. is handled by ParallelTest in TestBench, but there are a couple of useful things you can add to the abstract class.

Create a new class, AbstractTest in the com.example.application.it package. Be sure to place it in src/test/java and not src/main/java.

AbstractTest.java

  1. package com.example.application.it;
  2. import ch.qos.logback.classic.Level;
  3. import ch.qos.logback.classic.Logger;
  4. import com.vaadin.testbench.IPAddress;
  5. import com.vaadin.testbench.ScreenshotOnFailureRule;
  6. import com.vaadin.testbench.parallel.ParallelTest;
  7. import io.github.bonigarcia.wdm.WebDriverManager;
  8. import org.junit.Before;
  9. import org.junit.BeforeClass;
  10. import org.junit.Rule;
  11. import org.slf4j.LoggerFactory;
  12. public abstract class AbstractTest extends ParallelTest {
  13. private static final String SERVER_HOST = IPAddress.findSiteLocalAddress();
  14. private static final int SERVER_PORT = 8080;
  15. private final String route;
  16. static {
  17. // Prevent debug logging from Apache HTTP client
  18. Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
  19. root.setLevel(Level.INFO);
  20. }
  21. @BeforeClass
  22. public static void setupClass() {
  23. WebDriverManager.chromedriver().setup(); 1
  24. }
  25. @Rule 2
  26. public ScreenshotOnFailureRule rule = new ScreenshotOnFailureRule(this, true);
  27. @Before
  28. public void setup() throws Exception {
  29. super.setup();
  30. getDriver().get(getURL(route)); 3
  31. }
  32. protected AbstractTest(String route) {
  33. this.route = route;
  34. }
  35. private static String getURL(String route) {
  36. return String.format("http://%s:%d/%s", SERVER_HOST, SERVER_PORT, route);
  37. }
  38. }
  1. Start by invoking the WebDriverManager before any test method is invoked. TestBench does not invoke the web driver manager.

  2. ScreenshotOnFailureRule tells TestBench to grab a screenshot before exiting, if a test fails. This helps you understand what went wrong when tests do not pass.

  3. Open the browser to the correct URL before each test. For this, you need the host name where the application runs (“localhost” in development), the port the server uses (set to 8080 in application.properties), and information about the route to start from.

Testing the Login View

Now that your setup is complete, you can start developing your first test: ensuring that a user can log in. For this test you need to open the base URL.

Create a new class, LoginIT, in the same package as AbstractTest. The test validates that logging in with the correct user and password succeeds.

**LoginIT.java**

  1. package com.example.application.it;
  2. import com.vaadin.flow.component.login.testbench.LoginFormElement;
  3. import org.junit.Assert;
  4. import org.junit.Test;
  5. public class LoginIT extends AbstractTest {
  6. public LoginIT() {
  7. super("");
  8. }
  9. @Test
  10. public void loginAsValidUserSucceeds() {
  11. // Find the LoginForm used on the page
  12. LoginFormElement form = $(LoginFormElement.class).first();
  13. // Enter the credentials and log in
  14. form.getUsernameField().setValue("user");
  15. form.getPasswordField().setValue("userpass");
  16. form.getSubmitButton().click();
  17. // Ensure the login form is no longer visible
  18. Assert.assertFalse($(LoginFormElement.class).exists());
  19. }
  20. }
Note
Make sure tests have the correct name

The name of the class should end in ”IT” for the test runner to pick it up as an integration test. If you name it LoginTest instead, it will be run as a unit test and the server will not be started and the test will fail.

Tip
Start the server separately to speed up tests

While developing tests, it is not very efficient to run the tests as mvn -Pit verify. Instead, you can start the server manually by launching the Application class or with spring-boot:run. You can then execute the selected test in your IDE and you do not have to wait for the server to start every time.

Start the application normally, then right-click LoginIT.java and select Run ‘LoginIT’.

The first time you run the test, you will be asked to start a trial or validate your existing license. Follow the instructions in the browser window that opens.

Creating a View Object

You can now add a second test: validating that you cannot log in with an invalid password.

For this text, you need to write the same code to access the components in the view as you did for the first test. To make your tests more maintainable, you can create a view object (a.k.a. call page object or element class) for each view. A view object provides a high-level API to interact with the view and hides the implementation details.

For the login view, create the LoginViewElement class in a new package, com.example.application.it.elements:

LoginViewElement.java

  1. package com.example.application.it.elements;
  2. import com.vaadin.flow.component.login.testbench.LoginFormElement;
  3. import com.vaadin.flow.component.orderedlayout.testbench.VerticalLayoutElement;
  4. import com.vaadin.testbench.annotations.Attribute;
  5. @Attribute(name = "class", contains = "login-view")
  6. public class LoginViewElement extends VerticalLayoutElement {
  7. public boolean login(String username, String password) {
  8. LoginFormElement form = $(LoginFormElement.class).first();
  9. form.getUsernameField().setValue(username);
  10. form.getPasswordField().setValue(password);
  11. form.getSubmitButton().click();
  12. // Return true if we end up on another page
  13. return !$(LoginViewElement.class).onPage().exists();
  14. }
  15. }
Caution
Class hierarchies must match

To make the correct functionality available from superclasses, the hierarchy of the view object should match the hierarchy of the view (public class LoginView extends VerticalLayout vs public class LoginViewElement extends VerticalLayoutElement).

Adding the @Attribute(name = "class", contains = "login-view") annotation allows you to find the LoginViewElement using the TestBench query API, for example:

Finding a LoginViewElement using the TestBench query API

  1. LoginViewElement loginView = $(LoginViewElement.class).onPage().first();

The annotation searches for the login-view class name, which is set for the login view in the constructor. The onPage() call ensures that the whole page is searched. By default a $ query starts from the active element.

Now that you have the LoginViewElement class, you can simplify your loginAsValidUserSucceeds() test to be:

LoginIT.java

  1. @Test
  2. public void loginAsValidUserSucceeds() {
  3. LoginViewElement loginView = $(LoginViewElement.class).onPage().first();
  4. Assert.assertTrue(loginView.login("user", "userpass"));
  5. }

Add a test to use an invalid password as follows:

LoginIT.java

  1. @Test
  2. public void loginAsInvalidUserFails() {
  3. LoginViewElement loginView = $(LoginViewElement.class).onPage().first();
  4. Assert.assertFalse(loginView.login("user", "invalid"));
  5. }

Continue testing the other views by creating similar view objects and IT classes.

The next chapter covers how to make a production build of the application and deploy it to a cloud platform.

migration assistance

Download free e-book.
The complete guide is also available in an easy-to-follow PDF format.

https://pages.vaadin.com/en/build-a-modern-web-app-with-spring-boot-vaadin-pdf

Open in anew tab

Show code

render-banner.ts

  1. export class RenderBanner extends HTMLElement {
  2. connectedCallback() {
  3. this.renderBanner();
  4. }
  5. renderBanner() {
  6. let bannerWrapper = document.getElementById('tocBanner');
  7. if (bannerWrapper) {
  8. return;
  9. }
  10. let tocEl = document.getElementById('toc');
  11. // Add an empty ToC div in case page doesn't have one.
  12. if (!tocEl) {
  13. const pageTitle = document.querySelector(
  14. 'main > article > header[class^=PageHeader-module--pageHeader]'
  15. );
  16. tocEl = document.createElement('div');
  17. tocEl.classList.add('toc');
  18. pageTitle?.insertAdjacentElement('afterend', tocEl);
  19. }
  20. // Prepare banner container
  21. bannerWrapper = document.createElement('div');
  22. bannerWrapper.id = 'tocBanner';
  23. tocEl?.appendChild(bannerWrapper);
  24. // Banner elements
  25. const text = document.querySelector('.toc-banner-source-text')?.innerHTML;
  26. const link = document.querySelector('.toc-banner-source-link')?.textContent;
  27. const bannerHtml = `<div class='toc-banner'>
  28. <a href='${link}'>
  29. <div class="toc-banner--img"></div>
  30. <div class='toc-banner--content'>${text}</div>
  31. </a>
  32. </div>`;
  33. bannerWrapper.innerHTML = bannerHtml;
  34. // Add banner image
  35. const imgSource = document.querySelector('.toc-banner-source .image');
  36. const imgTarget = bannerWrapper.querySelector('.toc-banner--img');
  37. if (imgSource && imgTarget) {
  38. imgTarget.appendChild(imgSource);
  39. }
  40. }
  41. }