DEV Community

Cover image for Unit Testing with Javascript in a nutshell
Bee Bee Wijaya
Bee Bee Wijaya

Posted on

Unit Testing with Javascript in a nutshell

What is Unit Testing ?

Unit testing usually test a small part of the code. For example we test a function, we input something and we expect the function return something.

Look add the code in app.js below

We have a function named sum and it accept a & b arguments, and the function return the sum of a & b.

You're good ? Nice, now how we test this function and make sure it works like what we expected ?.

First let me introduced you to Jest

What is Jest ? it's just a testing library created and maintained by Facebook and you can find it more to learn in here.

But keep this in your head when you read this article, it doesn't matter if you not learn all the stuff in Jest, because you can still look up on it everytime you need the methods, it just syntax matter. What i mean is you must learn the concept and not the library.

Generate some new Projects

Lets generate some new Express Project for making a unit test app

~ mkdir learn_ut
~ cd learn_ut
~/learn_ut touch app.js
~/learn_ut yarn init -y
~/learn_ut yarn add express
~/learn_ut yarn add -D jest

Right, we're good. If you confused on this stuff then keep it simple, We're just generate a light Express applicaton here using yarn.

Now, let's config the jest in package.json file



I'm added the block code of Jest in that json file. What happened ? it just a small config for Jest to work on our project, That's all.

Also i added the scripts tag for us to run easily, usually this called npm scripts. for example, i don't need to run jest everytime on my terminal, so i just use yarn test.

All right, now let's create the test file and we must import the sum function in our test.

Oh my god, what's these new syntax ?

It's just a normal test syntax, a test() function is just like a statement of what you expect the return would be and it's accept a normal string in first argument and a callback in second argument, you can write whatever you want in first argument but i recommend you to write as what you expect the test would be.

Let's talk about the callback statement, here i expect the sum of 1 & 2 will be 3. expect() function is a Jest function and it has a bunch of method you can use like toBe() or toBeTruthy()etc.

What happened when you run the test ? Let's try it

~/learn_ut yarn test

Unit test result

All right!, we're done.

That's all for a Unit Testing in a nutshell.
I'm sorry if i can't write so good it's my first writing here, but i'm giving my best and i will contribute more in dev.to and for the Javascript community.

Wait for my next article, Thank you very much!

Oldest comments (0)