DEV Community

Sergii Kirianov
Sergii Kirianov

Posted on

Beginner's guide: Your first test

We always hear a lot about testing

We always hear a lot about testing. It's literally everywhere and many of us have no idea how to start, what tests to write, and what's the point of tests?

I'll try to give you a very basic introduction that will be easy to understand. We will use JavaScript and Jest Testing Framework. But first, let's start with very very basic stuff.

Why do we need tests?

Because.

rolling eyes gif

But if we talk seriously there are a lot of reasons for that, let's take a look at some:

  • You ensure your code is doing what it is supposed to do
  • You ensure that the app behaves as expected
  • You ensure people don't hate you
  • You prevent bugs creeping in

So that's fine, we all more or less understand that. Testing is something being done in any industry and this is in fact the standard. You can't neglect testing after a repair, manufacturing, or anything that may endanger somebody or destroy the user experience. Though it's heavily neglected with the beginners.

You may wonder - "I'm a beginner, why should I learn testing?". The answer is simple, many companies that are about to hire you, want you to understand the testing and at least have some minimal experience with it. If you cover your portfolio project with some unit testing - you're 100 steps away from your competitors.

Terminology

I don't understand these words

I'll make sure you understand.

Before we start, let's understand a few terms, nothing ultra-serious, but this will help you to understand a bit what are we even talking about.

  • Unit testing - "is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation." - in simple words, we are testing functions. We must test that function ALWAYS returns what we are expecting it to return.

  • Integration testing - "is a type of testing where software modules are integrated logically and tested as a group" - here you are testing different group components of the app to see that they work well together. Think of "if this is sent to the backend, this is what has to be received and displayed".

  • End-to-end testing - "is a methodology used in the software development lifecycle (SDLC) to test the functionality and performance of an application under product-like circumstances and data to replicate live settings. The goal is to simulate what a real user scenario looks like from start to finish". Quite self-descriptive, but to say it in human language - we are simulating user behavior. User visits this page - clicks this button - this modal opens - enters this data - submits - receives the result from BE.

I told you, simple tests first - Unit testing

Hope you're ready because this is going to be hard!
hardcore gif

Nah, it won't.

The good practice writing tests is following the TDD - Test Driven Development approach, but not in our case. Let's first understand how to write them, before going into complex details of the TDD approach.

Okay, let's write our first function. This is the approach I use when I have to write a function, so follow along.

**Task: **Write a function that takes a string of any size and creates an abbreviation.

Input: a string of any size

Desired output: an abbreviation consisting of concatenated capitalized first letters of each word in a string

Examples:

  • Input: "Advanced Business Application Programming" Output: "ABAP"
  • Input: "Object Oriented Programming" Output: "OOP"

Knowing this information we can split the task into small and easy-to-understand pieces.

// input: string = "Object oriented programming"

const createAbbreviation = (string) => {
  const arrayOfWords = string.split(' '); // ["Object", "oriented", "programming"]
  const arrayOfFirstLetters = arrayOfWords.map(word => word[0]); // ["O", "o", "p"]
  const stringOfFirstLetts = arrayOfFirstLetters.join(''); // "Oop"
  const upperCasedAbbreviation = stringOfFirstLetts.toUpperCase(); // "OOP"

  return upperCasedAbbreviation;
}

// output: "OOP"
Enter fullscreen mode Exit fullscreen mode

I think this function is simple enough, but if you want to be a bit "special", the following function is exactly the same.

const createAbbreviation = (string) =>
  string
    .split(' ')
    .map((word) => word[0])
    .join('')
    .toUpperCase();
Enter fullscreen mode Exit fullscreen mode

Okay, we have our function, we know what is it doing, so now we can think of a way to test it.
Let's initiate a project and install Jest.

Create a new folder and run npm init, just span Enter, we don't really care about our settings right now.

npm init terminal output

Now let's add Jest as a dev dependency. Open your VSCode and open the terminal. Once that is done, let's do the magic. Copy-paste this in your terminal and hit Enter: yarn add --dev jest. Congratulations, Jest is installed. In case you have an issue, please consult the docs. Few changes have to be made in your package.json, please go there and change the default test script command to this "test": "jest". Okay, you're all set, let's write that first test.

Create a new file named index.test.js - this is one of the default ways Jest can find test files. Usually, you don't write your functions inside test files, but we do it this way for the sake of simple configuration. Normally, you would have a dedicated file with functions and a separate file with tests.
And let's get to the interesting part.

Because of the way we thought of our function in the first place, we know what should be the input and what kind of output we should get. So let's do the same thing, but with JavaScript. Jest has its own syntax, so if you want to learn more - read docs. For now, we will use the most common syntax.

const createAbbreviation = (string) => {
  const arrayOfWords = string.split(' ');
  const arrayOfFirstLetters = arrayOfWords.map(word => word[0]);
  const stringOfFirstLetts = arrayOfFirstLetters.join('');
  const upperCasedAbbreviation = stringOfFirstLetts.toUpperCase();

  return upperCasedAbbreviation;
}

describe('Test createAbbreviation function', () => {
  it('creates abbreviation', () => {
    expect(createAbbreviation('European Union')).toEqual('EU');
    expect(createAbbreviation('Public Announcement')).toEqual('PA');
    expect(createAbbreviation('Very long name with more than five words')).toEqual('VLNWMTFW');
    expect(createAbbreviation('single')).toEqual('S');
  });
});
Enter fullscreen mode Exit fullscreen mode

Let's go line by line and see what this code is doing 👇

First, we create a test suite that defines the name of all tests inside it. A good practice is to have one single describe in the test file.

describe('name of the test suite', tests_functions);
Enter fullscreen mode Exit fullscreen mode

Then inside test suites, we are finally writing the actual tests.

it('name of the single test', single_test_function);
Enter fullscreen mode Exit fullscreen mode

Now, remember what we were talking about previously, we need to make sure that every time the input we give to a function always returns the exact same result. So, we are expecting the result of the function with example string to be equal to that output.

expect(createAbbreviation('European Union)).toEqual('EU');
Enter fullscreen mode Exit fullscreen mode

Hooray! Our first test is done! Now, let's run it! Go back to your VSCode terminal and type yarn jest to run the testing script and you should get something similar ❤️‍🔥

jest passed tests results

You're the boss

As you see, testing is not that hard and it's pretty easy to start with. If you approach a function/task in a proper way understanding what should be the output, you already know how to write the test. Of course, our function is very primitive and it does not include many edge cases, but for the sake of understanding, it's good enough.

If you're interested in E2E testing with Cypress you can check out my introduction article End-to-End testing with Cypress.

Thanks for your time and I hope this article opened up a door to the testing world for you. Even if just a bit ☺️

You can contact me on Twitter @SergiiKirianov if you have some questions, or leave them below in the comment section

Top comments (1)

Collapse
 
liviufromendtest profile image
Liviu Lupei • Edited

For anyone reading this, it's worth knowing that Cypress does not work on Safari.

And Safari is currently the 2nd most popular browser after Chrome:
techcrunch.com/2022/06/01/report-s...

Be sure to check the analytics data from your product, to know which browsers are being used, and to test on those browsers.

Remember, the rendering engines from browsers work in different ways.

Here's what happened to us when we didn't test properly in Safari:
endtest.io/guides/blog/2022/02/18/...