DEV Community

loading...
Cover image for Getting started with Jest in just 5 minutes

Getting started with Jest in just 5 minutes

ghana
Highly confident about what I do. Simply I have very good social skills
・2 min read

Testing with Jest, this may sound overwhelming but in fact getting started is very simple.

To get started let us test a simple function

const celsiusToFahrenheit = (temp) => {
    return (temp * 1.8) + 32
}
Enter fullscreen mode Exit fullscreen mode

Here we declared a function named celsiusToFahrenheit which takes in a parameter temp which is temperature and is of type number. It returns the Fahrenheit value of celsius temp.

Now let us test this!

Yeah, this our first test
First npm i -D jest here -D parameter to add it to dev dependency.
Next create a file name called anything.test.js, anything I mean literally anything.

test('Should convert 0 C to 32 F', () => {
    const temp = celsiusToFahrenheit(0)
    if(temp!==32) throw new Error("This Test Failed")
})
Enter fullscreen mode Exit fullscreen mode

Just paste this code and Voila! first test is done, Now let's dive into the code test() is a function that is made available globally by jest library when we installed. It takes two parameters, first one being simple the name of the test and second one being the testing function itself.
The testing function when finds an error then shows the output as failed this means a function with nothing inside still shows as a passed test

test('Dummy', () => {})
Enter fullscreen mode Exit fullscreen mode

The above test still passes.
But wait, what if there are many conditions to check or some asynchronous code?
Jest got our back

test('Should convert 0 C to 32 F', () => {
    const temp = celsiusToFahrenheit(0)
    expect(temp).toBe(32)
})
Enter fullscreen mode Exit fullscreen mode

Yes, expect is also a function provided in-built with jest package, now what that line means is - expect the temp variable to be a number 32 if not throw an error.
Now in terminal root project folder just run jest and see the passing test.

That's all and by the way this is my first blog post

Discussion (0)