SmartCodingTips

๐Ÿงช Testing JavaScript with Jest

Jest is a modern testing framework by Facebook that's great for testing JavaScript applications. It supports assertions, mocking, snapshot testing, and more.

๐Ÿ“ฆ Step 1: Install Jest

# Initialize project
npm init -y

# Install Jest
npm install --save-dev jest

Add this to your package.json to run tests using the npm test command:

"scripts": {
  "test": "jest"
}

๐Ÿงฎ Step 2: Write a Function to Test

// math.js
function add(a, b) {
  return a + b;
}
module.exports = add;

๐Ÿงช Step 3: Create a Test File

// math.test.js
const add = require('./math');

test('adds 2 + 3 to equal 5', () => {
  expect(add(2, 3)).toBe(5);
});

๐Ÿš€ Step 4: Run the Tests

npm test

Youโ€™ll see a green success message if everything is correct โœ…

๐Ÿ” Common Matchers

  • .toBe(value) โ€“ Exact match
  • .toEqual(object) โ€“ For objects/arrays
  • .toContain(item) โ€“ Check if array includes value
  • .toBeTruthy(), .toBeFalsy() โ€“ Booleans
  • .toThrow() โ€“ Expect error to be thrown

๐Ÿง  Mocking Example

Simulate a functionโ€™s behavior without calling the real implementation:

const fetchData = jest.fn(() => 'mocked data');
test('fetchData returns mocked data', () => {
  expect(fetchData()).toBe('mocked data');
});
โœ… Pro Tip: Place tests in a __tests__ folder or name them *.test.js for automatic discovery.