Course contentsShow
← JavaScript
Lesson 2672 of 2,72354. Testing in JavaScriptFree lesson

What Are Assertions?

Understanding assertions as statements that verify expected outcomes in tests.

What Are Assertions?

You'll learn what assertions are and why they form the foundation of every automated test.

The Core Idea

An assertion is a statement in your test code that declares what you expect to be true. It's the checkpoint that actually verifies whether your code behaves correctly. Without assertions, you'd just be running code without checking if it does the right thing.

Think of assertions like quality checkpoints on an assembly line. The machinery (your code) runs, but inspectors (assertions) verify that each widget meets specifications. If a widget fails inspection, the line stops and alerts are raised.

How Assertions Work

When you write a test, you typically:

  1. Set up some conditions
  2. Execute the code you want to test
  3. Assert that the outcome matches your expectations

That third step is the assertion. You're asserting—claiming with confidence—that something should be true. If it's not, the test fails and you know something's broken.

// Example structure (syntax varies by test runner)
it('should add two numbers correctly', () => {
  const result = add(2, 3);
  
  // This is an assertion:
  assert.strictEqual(result, 5); // "I assert that result equals 5"
});

The assertion checks whether result actually equals 5. If it doesn't, the test fails immediately with an error message.

Why Assertions Matter

Without assertions, your tests would execute code but never verify anything. You need assertions to transform "code that runs" into "code that proves correctness."

Key Takeaway: Assertions are verification statements that check whether actual outcomes match expected outcomes—they're the pass/fail checkpoints that give your tests meaning.