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

Negating Assertions with not

Using the not modifier to assert the opposite condition.

What You'll Learn

You'll learn how to flip an assertion to its opposite using the not modifier, making it easy to test that something isn't true without writing awkward logic.

The Core Idea

Sometimes you need to assert that something is not equal, not contained, or not thrown. Instead of wrapping your assertion in confusing logic or using a different matcher, most assertion libraries provide a not modifier that reverses the expectation.

Think of it like the "opposite day" rule: whatever you would normally expect to pass now needs to fail, and vice versa.

import assert from 'node:assert/strict';
import { describe, it } from 'node:test';

describe('not modifier', () => {
  it('asserts value is not equal', () => {
    const result = 5 + 3;
    assert.notEqual(result, 10); // Passes because 8 ≠ 10
  });

  it('asserts value is not strictly equal', () => {
    const result = '42';
    assert.notStrictEqual(result, 42); // Passes: string vs number
  });

  it('asserts string does not match pattern', () => {
    const message = 'Hello World';
    assert.doesNotMatch(message, /goodbye/i); // Passes
  });

  it('asserts function does not throw', () => {
    assert.doesNotThrow(() => {
      const x = 1 + 1;
    }); // Passes because no error is thrown
  });
});

When to Use not

Use negating assertions when the logic is clearer stated as an opposite. "This should not be zero" is often more readable than "This should be anything but zero." It keeps your test intentions explicit and your code cleaner.

Key Takeaway: The not modifier (or equivalent negation methods like notEqual, doesNotMatch) lets you assert the opposite condition cleanly, making negative test cases as readable as positive ones.