JavaScript Testing with Jest

Why Use Unit Testing ?

Installation

npm init
npm install --save-dev jest
--save-dev

A Very Basic Test

  1. Create a file named product.js and add the below code
"test": "echo \"Error: no test specified\" && exit 1"
"test": "jest"
npm run test
Notice the PASS indication and the description of the test below that in gray letters
If multiple tests fail, Jest will show multiple failures and where they occured

Testing Classes

example.js
example.test.js

Jest Matchers

  • toEqual() => recursively check every field of an object or array
  • toBeNull() => matches null only
  • toBeTruthy() => match anything treated as true in an if statement
  • toBeFalsy() => match anything treated as false in an if statement
  • toBeCloseTo() => to test floating point equality
  • toBeGreaterThan() => expectation is greater than
  • toBeLessThanOrEqual To() => expectation is less than or equal to
  • toMatch() => match strings against a regular expressions
  • toContain() => check if array or iterable contains particular item
  • toThrow() => check if function throws specific error

Asynchronous Tests

Asynchronous functions are declared with the async keyword
Note there are two options for running asynchronous tests above, by commenting out the previous ones you can test the later that use resolves() and rejects()

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aidan McBride

Aidan McBride

I ‘m a Web Developer and a Flatiron coding bootcamp alumni. I currently work in the financial tech industry as a Front End Engineer