Simplify testing with Cypress

Anyone who has ever started programming knows the situation. You write a component that works at first sight, but then has a lot of bugs when you use it. In the development phase this is quite natural, but if the application is handed over to a customer without much testing, so the big bang is not far away.

Now you sit there and have to test several 1000 elements, which affect every changes. Repeating tests several times is time-consuming and nerve-racking.

But fortunately there is the test framwork Cypress, which was developed especially for Web application.

The special thing about Cypress is that everything runs automatically. Manual clicking is a thing of the past.

You can read a detailed feature description at: https://docs.cypress.io/guides/overview/why-cypress.html#Our-mission

Start with Cypress

Install Cypress

First of all, we navigate to our project folder in the terminal and then install all the necessary packages there.

$ cd/your/project/path

npm:

$ npm install cypress --save-dev

yarn:

$ yarn add cypress --dev

Open Cypress

npm:

$ npx cypress open

yarn:

$ yarn run cypress open

Cypress User Interface

The main menu should look something like this:

As you can see, the tool already provides many finished examples. To check if everything works, you can simply click on a sample test and a new window will open where the test will be executed.

The Cypress Test-Runner opens and should look something like this:

The First Steps

In this section I will give you a short summary what you should know for the start.

1. create a test file

  • All test files come in the folder: cypress/intergration
  • naming convention: fileName_spec.js or fileName.spec.js
  • describe(), it(), context() and specify() contain the actual test and you can also use them to structure your test and give it a name.

File structure in an example:

// -- Start: Our Application Code --
function add (a, b) {
  return a + b
}
// -- End: Our Application Code --

// -- Start: Our Cypress Tests --
describe('Unit test our math functions', function() {
  context('math', function() {
    it('can add numbers', function() {
      expect(add(1, 2)).to.eq(3)
    })
})
// -- End: Our Cypress Tests --

2. Write test

As soon as you have created the test file, Cypress automatically updates the test list and your test should be selectable in the menu.

This section shows the basic functions.

Visit the test website: cy.visit()

This function checks the link and returns a true if a 2XX status like 200 is returned. Otherwise a false is returned and the test fails.

describe('My First Test', function() {
  it('Test PHMU Website', function() {
    cy.visit('https://www.phmu.de/')
  })
})
  • As you can see, the functions in the command log are displayed as uppercase letters. Here in our example VISIT.
  • A click on it, the addressed element is visually displayed in function.
  • All tests are displayed as a timeline and you can “jump back” the time and see exactly when and where the test failed or invoked.

Query elements

In Cypress we can query and pick an element from our test website . if it exist a true will be retrun

The common functions for this are:

contains(content) – Returns the DOM element containing the corresponding innerText..

describe('My First Test', function() {
  it('Test PHMU Website', function() {
    cy.visit('https://www.phmu.de/')
  })
  it('Test contain PHMU slogan', function() {
    cy.contains('Unser Herz schlägt digital')
  })
})

get(selector) – Returns the DOM element selected with the selector.

describe('My First Test', function() {
  it('Test PHMU Website', function() {
    cy.visit('https://www.phmu.de/')
  })
  it('Test contain PHMU slogan', function() {
    cy.get('img[class=image]')
    //Sucht ein img element mit der CSS-Klasse image
  })
})

Interacting with Elements

After you have queried the elements in the previous step, it is also possible to interact with the elements. If interaction with an element is not possible, the test will be displayed as failed.

type()

describe('My First Test', function() {
  it('Test contact formular', function() {
    cy.visit('https://www.phmu.de/workshops')
  })
  it('Test firstname input', function() {
    cy.get('input[id="firstname"]').type('Tung')
  })
})

click()

describe('My First Test', function() {
  it('Test contact formular', function() {
    cy.visit('https://www.phmu.de/workshops')
  })
  it('Test firstname input', function() {
    cy.get('button[id="submit"]').click()
  })
})

select()

describe('My First Test', function() {
  it('Test contact formular', function() {
    cy.visit('https://www.phmu.de/workshops')
  })
  it('Test firstname input', function() {
    cy.get('select[id="title"]').select("Doctor")
  })
})

Assertion

With should() you can check if an element is what you expect it to be. As an example, we want to make sure that the current URL is the expected URL.

describe('My First Test', function() {
  it('Test PHMU Website', function() {
    cy.visit('https://www.phmu.de/')
  })
  it('Test workshop link', function() {
    cy.get(a[href="/workshop"]).click
    cy.url().should('include', '/workshop')
  })
})

In this blog I have only given you the most necessary information for Cypress. Cypress is too big to put everything in one blog.

As I have already mentioned, I highly recommend you to read the documentation. Besides the good documentation it also contains Best Practices to test effectively.

Links

Vue Barcamp Berlin 2019

After months of waiting, the time had finally come. From October 25 to October 27, the PHMU team made their way to the federal capital, Berlin, with luggage and anticipation. The aim of the trip was the Vue Barcamp 2019.

Gruppe von PHMU

After the drive and arrival in Berlin, the discovery was the first thing on our to-do list. Right after the first step out of the train, we were struck by the size of Berlin. Day or night, there are crowds, music, lights. That’s when you first notice that Dresden is still a small, manageable city. After we let off steam, we went to the hotel to prepare for an interesting day.

Day 1

After we arrived at the venue on time, despite getting on the wrong track, the bar camp started immediately.

At a Barcamp, participants plan the program themselves by presenting a topic or suggesting a problem that they want to discuss. Then, according to the number of interested parties, the topic is added to the program or not.

Vue Barcamp Präsentation

This enabled enough topics to be found on the first day to fill a whole day and beyond.

Programm Barcamp Vue
Program schedule for Saturday

From workshops for Vue.js beginners, frameworks announcements to discussions about the upcoming update for Vue.js 3.0, everything was there.

Diskussion Barcamp Vue
Discussion about what’s new in Vue.js 3.0
Philipp von PHMU auf Barcamp Vue
Phillipp told the community about his work with Storybook

Day 2

On the second day, the program was again full of interesting content, stimulated by discussions and topics on the previous day.

Barcamp Vue

My experience

As you can see, the Barcamp draws its charm from the exchange of information among Vue.js developers. As in life, it follows the principle of giving and take. By sharing our experiences from our projects with the Vue.js community, we receive lots of good suggestions for future projects from the community.

Ramona from Shopware was kind and introduced us to the cypress.io test framework on the first day and we were immediately impressed. This has led us to work with the framework in our future projects.

All in all, the Vue Barcamp was an exciting event. In the beginning, as a Vue.js beginner, I was very afraid of getting lost in the eddy current of expert words. But as it turned out, many participants had just started with Vue.js themselves or who wanted to learn it. So the fear was wrong. Since the topics are broad, there is always a topic for every skill level. I can warmly recommend such a Barcamp to everyone. It doesn’t always have to be Vue.js 😉

Sending emails with Netlify Functions

Let’s say you’ve built your first modern static website (JAMStack) and want to make it more dynamic, e.g. by sending emails with dynamic content and file attachments. But you don’t want to set up or use your server for this. We explain how to do this in this post.

What do you need?

1. Mailing service

First of all, you need a mailing service that sends your emails. You shouldn’t send emails from your email server, but use a larger service provider to avoid the risk of being classified as a spam sender, for example. To send an email, you address the service API with an API key and hand over all the data that should be contained in the email and the mailing service then sends it to the target address.

There are many services to choose from and you should choose the one that suits you best in terms of features and price. Since I enjoyed working with POSTMARK on my last project, in this post I will introduce how to use this service.

2. Netlify

Next, we need a small amount of server-side code to protect the API key on the API request. Lambda functions are ideal for this. A URL endpoint is called up and a given code is executed when it is called. Netlify supports this, so it would be a good idea to host your site on it.

Step 1: Set up the mail service

Set up POSTMARK

The first thing we do is log into Postmark and go through all the steps until we get to the dashboard and have access to the API token.

API Token

Provide the API key for Netlify

To protect the API key, the key should only be made available when executing server-side codes. In Netlify we have to assign the key to a variable under “Environment”.

API Key Environment

Step 2: write functions

How do we create a Netlify function? Very easily. In your project folder, you create a folder with the name “functions”. In this, you then create all the JavaScript files that you need. In our case, we create the file send-email.js.

/project
   ... your entire website or whatever ...
   /functions/
         send-email.js

Use Postmark Node Library

Postmark provides its Node.js library and with a look at the documentation, we discover a simple code example for testing right at the beginning.

const serverToken = "xxxx-xxxxx-xxxx-xxxxx-xxxxxx" //API Key
let postmark = require("postmark")
let client = new postmark.ServerClient(serverToken);

exports.handler = (event, context, callback) => {
client.sendEmail(
    {
        From: "from@example.com", //Deine Emailadresse
        To: "to@example.com", //Ziel Emailadresse
        Subject: "test email",
        HtmlBody: "test",
        TextBody: "test"
    }
).then(response => {
    console.log(response.To);
    console.log(response.SubmittedAt);
    console.log(response.Message);
    console.log(response.MessageID);
    console.log(response.ErrorCode);
});
}

If you are new or not familiar with the AWS Lambda functions – no problem! I’ll give you a brief overview of the individual parameters that our handler receives.

  • event is an object that contains data on the request
  • context contains the user information when using Identity for user authentication
  • callback is a function we can use to create a response

With the callback () method we can test whether our request has arrived at the Mailing Service API.

  callback(null, {
    statusCode: 200,
    body: 'I am on my way !'
  })
}

Step 3: testing

Netlify Dev

Now we have written our first Netlify function and would like to test our work. There is a small tool for this called Netlify Dev. With it, we can simulate a dev server that gives us a local URL with which we can execute and test our functions in the development environment.

After installing and running it should look something like this:

Netlify Dev

Testing the function

To call our Lambda function, we need to address it with a URL like the one below:

http://localhost:8888/.netlify/functions/send-email

If everything went well, the recipient will be happy about your first email 🙂

Testing E-Mail

Step 4: Fill the email with data

Congratulations, you have now sent your first email with the Netlify function. Unfortunately, the content is still static and boring. To breathe new life into your mail, we need to make the code more dynamic.

Let’s say you want to email several congratulations to friends and add a text file with a personal message as an attachment.

You fill in all data with a form and these are saved as an object, e.g .:

const congratulation = {
  targetEmail: "test@gmail.com", 
  reason: "Geburtstag",
  firstname: "Peter",
  message: "Alles Gute zum Geburtstag. Es freut mich das du erwachsen 
           wirst"
}

Now, this data has to be transferred to the URL of the send-mail.js function when sending. To do this, we use an HTTP request with the URL function as the target address with the form data as the payload.

axios({
          method: 'POST',
          headers: { 'content-type': 'application/json' },
          url: '/.netlify/functions/send-email',
          data: congratulation, //payload
      })

Next, we have to fill the content of the e-mail with the data from the payload in our send-mail.js function. It is advisable to use console.log (event) when developing to display all data from the request in the terminal.

Netlify E-Mail

To add an attachment, just take a look at the Postmark Node.js documentation.

const attachment = new 
                    postmark.Models.Attachment("Glückwunschtext.txt", 
                    Buffer.from("payload.message").toString("base64"), 
                    "text");

client.sendEmail(
    {
        From: "from@example.com", //Deine Emailadresse
        To: "to@example.com", //Ziel Emailadresse
        Subject: "test email",
        HtmlBody: "test",
        TextBody: "test"
        Attachments: [attachment],
    })

The fully adapted function then looks like this in the end.

const serverToken = "xxxx-xxxxx-xxxx-xxxxx-xxxxxx" //API Key
let postmark = require("postmark")
let client = new postmark.ServerClient(serverToken);

exports.handler = (event, callback) => {
console.log(event) 
const payload = JSON.parse(event.body)

 const attachment = new 
                    postmark.Models.Attachment("Glückwunschtext.txt", 
                    Buffer.from("payload.message").toString("base64"), 
                    "text");

client.sendEmail(
    {
        From: "tung@phmu.de", //Deine Emailadresse
        To: payload.targetEmail, //Ziel Emailadresse
        Subject: payload.reason, 
        TextBody: `Liebe ${payload.firstname}, 
                  du hast eine Glückwunschemail erhalten`,
        Attachments: [attachment],
    })
} 

The content of the emails sent should then look like this:

Von: tung@phmu.de
An: test@gmail.com
Betreff: Geburtstag

Anhang: Glückwunschtext.txt

Nachricht: 
Liebe Peter, 
du hast eine Glückwunschemail erhalten             

As you can see, sending emails with Netlify Functions is not that complicated. You could now make the emails even fancier such as B. Add HTML code and … But I’ll leave that to you 😉