Перейти к основному содержимому
← ⚡ JavaScript & the browser·Модуль C8 · Урок 1
ЗаданиеDefine assert(cond, msg) that throws Error('assert: ' + msg) when !cond. Define assertEqual(actual, expected, msg) that throws when actual !== expected with a clear message. Call assert(2+2===4, 'math'); assertEqual(2+2, 4, 'sum'); try assertEqual(1,2,'one') in try/catch and log err.message.

Assertion functions — the foundation

75 XP6 min
Теория

What an assertion is

An assertion is a function that throws if its condition is false. That's it. Every test framework — node:test, Vitest, Jest — is built on top of this two-line primitive.

function assert(cond, msg) {
  if (!cond) throw new Error("assertion failed: " + (msg || "no message"));
}
assert(1 + 1 === 2, "math still works"); // passes silently
assert(1 + 1 === 3, "math broke");       // throws

Why this is the right starting point

  • No magic. You can implement it yourself in 30 seconds.
  • Composes with try/catch — a test that doesn't throw is a passing test.
  • Stack trace points at the assertion line, not the helper.

assertEqual

A common shortcut for equality checks — same idea, better failure message:

function assertEqual(actual, expected, msg) {
  if (actual !== expected) {
    throw new Error(`${msg || "values differ"}: got ${actual}, expected ${expected}`);
  }
}

This is the entire skeleton. C8-02 makes the failure message useful for objects.

🔒

Зарегистрируйся чтобы кодить

Теория открыта всем. Интерактивный редактор, живой превью и проверка открываются с 7-дневным бесплатным trial — нужна карта, отмена в любое время.

Регистрация — бесплатный trial →

Первые 10 уроков в каждом треке — бесплатные. Карта не нужна.

← НазадСледующий урок →

Получай один совет по Python или веб-разработке — каждый день в почте

Коротко, без воды, без спама. Отписаться — в один клик.