Published on

End-to-end testing with Cypress for Laravel Developers

Authors

In this short article, I want to share how fast and easy you can set up and start testing your Laravel application with Cypress, amazing tool for front end testing. Here you can find the Github repository with Cypress tests for basic login and registration functionality in Laravel.

Cypress end-to-end testing in Laravel

After fresh Laravel installation let’s enable basic login/registration functionality with php artisan make:auth command. So we have something to test. Then install Cypress and Faker (we need it for fake data generation in our tests).

yarn add cypress faker --dev

Now we can run ./node_modules/.bin/cypress open to scaffold Cypress folder structure and open test runner. I recommend adding this command into your package.json file as the scripts section. This is all we need to start writing tests with Cypress 😉!

Create a Test File

After successful initial set up we are ready to create the test file. Just create the new file registration.spec.js located incypress/integration folder. The syntax for tests is the same as for other js tests framework: describe and it blocks. Our test for registration functionality can look like the code below:

import faker from 'faker'

describe('Registration', () => {
  const email = faker.internet.email()
  const password = faker.internet.password()
  it('successfully registering', () => {
    cy.visit('http://127.0.0.1:8000/register')
    cy.get('input[name=name]').type(faker.name.findName())
    cy.get('input[name=email]').type(email)
    cy.get('input[name=password]').type(password)
    cy.get('input[name=password_confirmation]').type(password)
    cy.get('button').contains('Register').click()
    cy.url().should('contain', '/home')
    cy.get('#navbarDropdown').click()
    cy.contains('Logout').click()
  })
})

Here we visit the registration page (don’t forget to fire up the local server with the command php artisan serve), populate input fields, click the submit button and then make the assertion that we redirected to dashboard by checking the url. The whole test suite you can find here. Now we can execute our tests with Cypress test runner.

Cypress Tests in Action

Testing in action

That’s it :-) In this article I wanted to give the introduction into front end testing with Cypress, the tool for modern and next generation end-to-end testing tool. You can see that set up, write and run tests with Cypress is fast and easy. For more info please check Cypress Docs and Github repository, which I created for this article.

If you have any questions regarding the article or any other topics, you can reach me via comments here or through DM on twitter @olefyrenko. Thank you!