Cypress is Just JavaScript

Generating Tests Dynamically with Lodash

It is important to recognize that Cypress is just JavaScript. For example, here is a test where we are using _.each from Lodash to dynamically create tests.

By the way, did you know that Cypress natively imports Lodash? You can use Lodash in your tests by importing it, as you see in the example below.

const { _ } = Cypress // importing lodash

_.each(feedViews, (feed, feedName) => {
      it(`paginates ${feedName} transaction feed`, () => {
        cy.getBySelLike(feed.tab)
          .click()
          .should("have.class", "Mui-selected")
          .contains(feed.tabLabel, { matchCase: false })
          .should("have.css", { "text-transform": "uppercase" });
        cy.getBySel("list-skeleton").should("not.exist");
        cy.visualSnapshot(`Paginate ${feedName}`);

        cy.wait(`@${feed.routeAlias}`)
          .its("response.body.results")
          .should("have.length", Cypress.env("paginationPageSize"));
// ...

This example comes from the Real World App.

Using Array.forEach()

Here is another example where we use Array.forEach() to iterate over an array.

const people = ["moe", "curly", "larry"]
// Use method from lodash to get a person to use in a comment
const transactions = [{ id: 1 }]
_.each(transactions, () => {
  it("comments on a transaction", () => {
    cy.getBySelLike("transaction-item").first().click()
    cy.wait("@getTransaction")

    const comments = ["Thank you!", "Appreciate it."]

    comments.forEach((comment, index) => {
      cy.getBySelLike("comment-input").type(`${comment}{enter}`)
      cy.getBySelLike("comments-list").children().eq(index).contains(comment)
    })

    cy.getBySelLike("comments-list")
      .children()
      .should("have.length", comments.length)
    cy.visualSnapshot("Comment on Transaction")
  })
})

Wrap Up

Congrats! You have finished the third course of Real World Testing with Cypress. In the next course you will learn some of the more advanced concepts in Cypress that take your tests to the next level.


Unlock the next lesson

Using lots of variables in your tests is a good idea since Cypress is just JavaScript.