DEV Community

Cover image for How to Test URL param with Spaces
Cath Leyson
Cath Leyson

Posted on

How to Test URL param with Spaces

Introduction

When testing applications that involve URL parameters, it's important to ensure that the parameters are encoded correctly, especially when they contain spaces or special characters. In this article, we will explore how to test URL parameters with spaces in Cypress using a practical example.

Setting up the Test

To begin, create a new Cypress test file called "search.spec.ts" in the "cypress/integration" directory. This file will contain our test case for searching a hero name in the search bar.

describe("Search results", () => {
  it("types hero name in search bar", () => {
    cy.visit("http://localhost:3000/home");

    cy.get('[data-cy="search-bar"]')
      .type("iron man")
      .should(
        "have.value",
        "iron man",
        `/characters?nameStartsWith=${encodeURIComponent("iron man")}`
      );
  });
});
Enter fullscreen mode Exit fullscreen mode

In this test case, we navigate to the homepage and type "iron man" in the search bar. We then assert that the input value matches "iron man" and that the resulting URL contains the encoded parameter "nameStartsWith=iron%20man" (where "%20" represents the space character).

Testing URL Parameters with Spaces

To test the URL parameter with spaces, we need to ensure that the parameter is correctly encoded before asserting its presence in the URL.

cy.should(
  "have.value",
  "iron man",
  `/characters?nameStartsWith=${encodeURIComponent("iron man")}`
);
Enter fullscreen mode Exit fullscreen mode

The encodeURIComponent function converts special characters, including spaces, to their URL-encoded representations. By passing the "iron man" value through this function, we can safely include it in the URL.

Conclusion

Testing URL parameters with spaces is essential to ensure that your web application handles them correctly.

By using the encodeURIComponent function and asserting the encoded parameter in the URL, you can confidently test scenarios where URL parameters contain spaces or special characters.

Hope this helps!

Top comments (0)