🔹 What is Jasmine?
- Jasmine is a behavior-driven development (BDD) testing framework for JavaScript.
- It’s mainly used to test JavaScript code (both frontend and backend).
- It provides functions like
describe()
,it()
, andexpect()
to write human-readable tests. - No need for DOM or browser—it can run independently.
🔹 What is Karma?
- Karma is a test runner developed by the AngularJS team.
- It doesn’t test by itself—it just runs your Jasmine (or Mocha, etc.) tests in multiple real browsers.
- It helps automate running tests every time you make changes.
- Works well with CI/CD pipelines.
👉 Think of it this way:
- Jasmine = the testing framework (how to write tests).
- Karma = the test runner (where and how to run those tests).
🔹 Example: Jasmine + Karma Setup
Let’s say we have a simple function:
// math.js
function add(a, b) {
return a + b;
}
Now, a Jasmine test would look like this:
// math.spec.js
describe("Add function", function() {
it("should return the sum of two numbers", function() {
expect(add(2, 3)).toBe(5);
});
it("should handle negative numbers", function() {
expect(add(-2, -3)).toBe(-5);
});
});
🔹 Running with Karma
- Install dependencies:
npm install --save-dev karma jasmine-core karma-jasmine karma-chrome-launcher
- Create
karma.conf.js
(Karma config file): - Run tests:
npx karma start
module.exports = function(config) {
config.set({
frameworks: ["jasmine"], // use Jasmine
files: [
"math.js",
"math.spec.js"
],
browsers: ["Chrome"], // run tests in Chrome
singleRun: true
});
};
Karma will open Chrome, run your Jasmine tests, and report results in the terminal.
✅ Summary:
- Jasmine → used to write tests (assertions, test suites).
- Karma → used to run tests (in browsers, CI/CD, automated runs).