DEV Community

Cover image for How to check the contents of a file with Cypress
Walmyr Filho
Walmyr Filho

Posted on • Updated on

How to check the contents of a file with Cypress

Did you know that with Cypress, it is possible to read the contents of a file?

Today in "Pinches of Cypress", learn how it works.

To facilitate the explanation, I will use an example of the course of the automated tests with Cypress intermediate, from the TAT School.

In the course, the application under test is the open-source version of GitLab.

Among the questions related to the optimization of graphical user interface tests, during the course, I also teach how to use Cypress to interact with the application at the operating system level, such as the execution of an instruction via the command line to clone a project.

Let's look at an example.

const faker = require('faker')

describe('git clone', () => {
  const project = {
    name: `project-${faker.random.uuid}`,
    description: `faker.random.words(5)`
  }

  beforeEach(() => cy.api_createProject(project))

  it('successfully', () => {
    cy.cloneViaSSH(project)

    cy.readFile(`temp/${project.name}/README.md`)
      .should('contain', `# ${project.name}`)
      .and('contain', project.description)
  })
})
Enter fullscreen mode Exit fullscreen mode

In the it block, I invoke the custom command cloneViaSSH passing the project object as an argument, and then I use the readFile command passing the README.md file of the newly cloned project as an argument. Finally, I verify that the project's name is contained as the title of the file and that its description is also contained in it.

Let me show you the custom command that clones the project.

Cypress.Commands.add('cloneViaSSH', project => {
  const domain = Cypress.config('baseUrl').replace('http://', '').replace('/', '')

  cy.exec(`cd temp/ && git clone git@${domain}:${cypress.env.user_name}/${project.name}.git`)
})
Enter fullscreen mode Exit fullscreen mode

That's it!


Did you like it?

Leave a comment with what I should write in an upcoming "Pinch of Cypress".


This post was originally published in Portuguese on the Talking About Testing blog.


Would you like to learn about test automation with Cypress? Get to know my online courses on Udemy.

Discussion (0)