Assert moduli


ULASHISH

Assert moduli nima?

Assert moduli kodingizdagi invariantlarni tekshirish uchun oddiy, ammo kuchli tasdiq testlarini taqdim etadi.

Bu o‘rnatishni talab qilmaydigan asosiy Node.js moduli.

Asosiy xususiyatlarga quyidagilar kiradi:

  • Oddiy haqiqat/yolg‘on da’volar
  • Qattiq va erkin tenglikni tekshirish
  • Chuqur obyektni taqqoslash
  • Otish va ishlov berishda xatolik
  • Asenkron/kutish naqshlarini qo‘llab-quvvatlash

Eslatma: Jest yoki Mocha kabi test tizimlari kabi funksiyalarga boy bo‘lmasa-da, Assert moduli yengil va oddiy sinov ehtiyojlari uchun yoki tashqi bog‘liqliklardan qochish uchun juda mos keladi.


Assert bilan ishlashni boshlash

Oddiy funksiyani sinab ko‘rish uchun Assert modulidan foydalanishning tezkor misoli:

Asosiy tasdiqlash misoli

const assert = require('assert').strict;

// Function to test
function add(a, b) {
  if (typeof a !== 'number' || typeof b !== 'number') {
    throw new TypeError('Inputs must be numbers');
  }
  return a + b;
}
// Test cases
assert.strictEqual(add(2, 3), 5, '2 + 3 should equal 5');
// Test error case
assert.throws(
  () => add('2', 3),
  TypeError,
  'Should throw TypeError for non-number input'
);
console.log('All tests passed!');
Misolni ishga tushirish »

Import va sozlash

Node.js ilovangizda Assert modulini import qilish va undan foydalanishning bir necha usullari mavjud:

CommonJS importi (Node.js)

// Basic require
const assert = require('assert');

// Using strict mode (recommended)
const assert = require('assert').strict;

// Destructuring specific methods
const { strictEqual, deepStrictEqual, throws } = require('assert');

// For async/await tests
const { rejects, doesNotReject } = require('assert').strict;

ES modullari (Node.js 12+)

// Using default import
import assert from 'assert';

// Using strict mode with ESM
import { strict as assert } from 'assert';

// Importing specific methods
import { strictEqual, deepStrictEqual } from 'assert';

// Dynamic import
const { strict: assert } = await import('assert');

Eng yaxshi amaliyot: Qattiq rejim tavsiya etiladi, chunki u aniqroq taqqoslash va yaxshiroq xato xabarlarini beradi.

Shuningdek, u Node.js ning kelajakdagi versiyalari bilan ko‘proq mos keladi, bu yerda qat’iy rejim standart bo‘ladi.



Tasdiqlashning asosiy usullari

Assert moduli kodingizdagi qiymatlar haqida tasdiqlash uchun bir necha usullarni taqdim etadi.

Ushbu usullar Assert moduli bilan sinovning asosini tashkil qiladi.

assert(value[, message])

Qiymat rost yoki yo‘qligini tekshiradi. Agar qiymat noto‘g‘ri bo‘lsa, AssertionError yuboriladi.

const assert = require('assert');

// This will pass
assert(true);
assert(1);
assert('string');
assert({});

try {
  // This will throw an AssertionError
  assert(false, 'This value is not truthy');
} catch (err) {
  console.error(`Error: ${err.message}`);
}

try {
  // These will also throw errors
  assert(0);
  assert('');
  assert(null);
  assert(undefined);
} catch (err) {
  console.error(`Error: ${err.message}`);
}
Misolni ishga tushirish »

assert.ok(value[, message])

Bu assert() uchun taxallus.

const assert = require('assert');

// These assertions are equivalent
assert.ok(true, 'This value is truthy');
assert(true, 'This value is truthy');

Qiymatni taqqoslash

Assert moduli qiymatlarni solishtirishning bir nechta usullarini taqdim etadi, ularning har biri majburlash turi va obyektni taqqoslash bo‘yicha har xil xatti-harakatlarga ega.

assert.equal(actual, expected[, message])

actual va expected parametrlari orasidagi yuzaki, tiplarni moslashtiruvchi tenglikni tenglik operatori (==) yordamida tekshiradi.

const assert = require('assert');

// These will pass (coercive equality)
assert.equal(1, 1);
assert.equal('1', 1); // String is coerced to number
assert.equal(true, 1); // Boolean is coerced to number

try {
  // This will throw an error
  assert.equal(1, 2, '1 is not equal to 2');
} catch (err) {
  console.error(`Error: ${err.message}`);
}
Misolni ishga tushirish »

assert.strictEqual(actual, expected[, message])

actual va expected parametrlari orasidagi qat’iy tenglikni qat’iy tenglik operatori (===) yordamida tekshiradi.

const assert = require('assert');

// This will pass
assert.strictEqual(1, 1);

try {
  // These will throw errors (strict equality)
  assert.strictEqual('1', 1, 'String "1" is not strictly equal to number 1');
  assert.strictEqual(true, 1, 'true is not strictly equal to 1');
} catch (err) {
  console.error(`Error: ${err.message}`);
}
Misolni ishga tushirish »

Eng yaxshi amaliyot: Kutilmagan turdagi majburlash muammolarining oldini olish uchun strictEqual() dan equal() dan foydalanish tavsiya etiladi.


Obyekt va massivni solishtirish

Obyektlar va massivlar bilan ishlaganda, ularning havolalarini emas, balki ularning mazmunini solishtirish uchun chuqur tenglik tekshiruvlaridan foydalanishingiz kerak bo‘ladi.

Obyektlar va massivlarni taqqoslash uchun Node.js chuqur tenglik funksiyalarini ta’minlaydi:

assert.deepEqual(actual, expected[, message])

actual va expected parametrlari orasidagi chuqur tenglikni erkin tenglik (==) bilan tekshiradi.

assert.deepStrictEqual(actual, expected[, message])

actual va expected parametrlari orasidagi chuqur tenglikni qat’iy tenglik (===) bilan tekshiradi.

const assert = require('assert');

// Objects with the same structure
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { a: 1, b: { c: 2 } };
const obj3 = { a: '1', b: { c: '2' } };

// These will pass
assert.deepEqual(obj1, obj2);
assert.deepStrictEqual(obj1, obj2);

// This will pass (loose equality)
assert.deepEqual(obj1, obj3);

try {
  // This will throw an error (strict equality)
  assert.deepStrictEqual(obj1, obj3, 'Objects are not strictly deep-equal');
} catch (err) {
  console.error(`Error: ${err.message}`);
}

// Arrays
const arr1 = [1, 2, [3, 4]];
const arr2 = [1, 2, [3, 4]];
const arr3 = ['1', '2', ['3', '4']];

// These will pass
assert.deepEqual(arr1, arr2);
assert.deepStrictEqual(arr1, arr2);

// This will pass (loose equality)
assert.deepEqual(arr1, arr3);

try {
  // This will throw an error (strict equality)
  assert.deepStrictEqual(arr1, arr3, 'Arrays are not strictly deep-equal');
} catch (err) {
  console.error(`Error: ${err.message}`);
}
Misolni ishga tushirish »

Tengsizlik va inkor

Tenglikni tekshirish qanchalik muhim bo‘lsa, qadriyatlar teng bo‘lmasligi kerak bo‘lganda teng emasligini tekshirishdir.

assert.notEqual(actual, expected[, message])

actual va expected parametrlari orasidagi yuzaki, tiplarni moslashtiruvchi tengsizlikni tengsizlik operatori (!=) yordamida tekshiradi.

assert.notStrictEqual(actual, expected[, message])

actual va expected parametrlari orasidagi qat’iy tengsizlikni qat’iy tengsizlik operatori (!==) yordamida tekshiradi.

const assert = require('assert');

// These will pass
assert.notEqual(1, 2);
assert.notStrictEqual('1', 1);

try {
  // This will throw an error
  assert.notEqual(1, '1', '1 is coercively equal to "1"');
} catch (err) {
  console.error(`Error: ${err.message}`);
}

try {
  // This will throw an error
  assert.notStrictEqual(1, 1, '1 is strictly equal to 1');
} catch (err) {
  console.error(`Error: ${err.message}`);
}
Misolni ishga tushirish »

Chuqur tengsizlik

assert.notDeepEqual(actual, expected[, message])

Bo‘shashgan tengsizlik bilan chuqur tengsizlik uchun testlar.

assert.notDeepStrictEqual(actual, expected[, message])

Qattiq tengsizlik bilan chuqur tengsizlik uchun testlar.

const assert = require('assert');

const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 3 };
const obj3 = { a: '1', b: '2' };

// These will pass
assert.notDeepEqual(obj1, obj2);
assert.notDeepStrictEqual(obj1, obj2);
assert.notDeepStrictEqual(obj1, obj3);

try {
  // This will throw an error (loose equality)
  assert.notDeepEqual(obj1, obj3, 'obj1 is loosely deep-equal to obj3');
} catch (err) {
  console.error(`Error: ${err.message}`);
}
Misolni ishga tushirish »

Xato bilan ishlash

Sizning kodingiz kutilgan xatolarga yo‘l qo‘yishini tekshirish mustahkam ilovalarni yozishning muhim qismidir.

Assert moduli buning uchun bir qancha usullarni taqdim etadi.

assert.throws(fn[, error][, message])

fn funksiyasi xato chiqishini kutadi. Aks holda, AssertionError yuboriladi.

const assert = require('assert');

// Function that throws an error
function throwingFunction() {
  throw new Error('Error thrown');
}

// This will pass
assert.throws(throwingFunction);

// Check for a specific error message
assert.throws(
  throwingFunction,
  /Error thrown/,
  'Unexpected error message'
);

// Check for a specific error type
assert.throws(
  throwingFunction,
  Error,
  'Wrong error type'
);

// Check with a validation function
assert.throws(
  throwingFunction,
  function(err) {
    return err instanceof Error && /thrown/.test(err.message);
  },
  'Error validation failed'
);

try {
  // This will throw an AssertionError
  assert.throws(() => {
    // This function doesn't throw
    return 'no error';
  }, 'Expected function to throw');
} catch (err) {
  console.error(`Error: ${err.message}`);
}
Misolni ishga tushirish »

assert.doesNotThrow(fn[, error][, message])

fn funksiyasi xatolikka yo‘l qo‘ymasligini kutadi. Agar shunday bo‘lsa, xato tarqaladi.

const assert = require('assert');

// This will pass
assert.doesNotThrow(() => {
  return 'no error';
});

try {
  // This will throw the original error
  assert.doesNotThrow(() => {
    throw new Error('This will be thrown');
  }, 'Unexpected error');
} catch (err) {
  console.error(`Error: ${err.message}`);
}
Misolni ishga tushirish »

Asinxron kodni sinovdan o‘tkazish

Zamonaviy JavaScript asinxron naqshlardan ko‘p foydalanadi.

Assert moduli Promise-ga asoslangan va callback funksiyasiqa asoslangan asinxron kodni sinab ko‘rish uchun yordamchi dasturlarni taqdim etadi.

assert.rejects(asyncFn[, error][, message])

asyncFn Promise obyekti yoki asinx funksiyasini kutadi va uni rad etishini kutadi.

const assert = require('assert');

async function asyncTest() {
  // Function that returns a rejecting promise
  function failingAsyncFunction() {
    return Promise.reject(new Error('Async error'));
  }

  // This will pass
  await assert.rejects(
    failingAsyncFunction(),
    /Async error/
  );

  // This will also pass
  await assert.rejects(
    async () => {
      throw new Error('Async function error');
    },
    {
      name: 'Error',
      message: 'Async function error'
    }
  );

  try {
    // This will throw an AssertionError
    await assert.rejects(
      Promise.resolve('success'),
      'Expected promise to reject'
    );
  } catch (err) {
    console.error(`Error: ${err.message}`);
  }
}

// Run the async test
asyncTest().catch(err => console.error(`Unhandled error: ${err.message}`));
Misolni ishga tushirish »

assert.doesNotReject(asyncFn[, error][, message])

asyncFn Promise-ini yoki asinx funksiyasini kutadi va uning bajarilishini kutadi.

const assert = require('assert');

async function asyncTest() {
  // This will pass
  await assert.doesNotReject(
    Promise.resolve('success')
  );

  // This will also pass
  await assert.doesNotReject(
    async () => {
      return 'async function success';
    }
  );

  try {
    // This will throw the original rejection reason
    await assert.doesNotReject(
      Promise.reject(new Error('Failure')),
      'Expected promise to fulfill'
    );
  } catch (err) {
    console.error(`Error: ${err.message}`);
  }
}

// Run the async test
asyncTest().catch(err => console.error(`Unhandled error: ${err.message}`));
Misolni ishga tushirish »

Boshqa tasdiqlash usullari

assert.match(string, regexp[, message])

Kiritilgan string muntazam ifodaga mos kelishini kutadi.

const assert = require('assert');

// This will pass
assert.match('I love Node.js', /Node\.js/);

try {
  // This will throw an AssertionError
  assert.match('Hello World', /Node\.js/, 'String does not match the pattern');
} catch (err) {
  console.error(`Error: ${err.message}`);
}
Misolni ishga tushirish »

assert.fail([message])

Taqdim etilgan xabar yoki standart xabar bilan AssertionError ni chiqaradi.

const assert = require('assert');

try {
  // This always throws an AssertionError
  assert.fail('This test always fails');
} catch (err) {
  console.error(`Error: ${err.message}`);
}
Misolni ishga tushirish »

Qattiq rejim

Node.js barcha taqqoslashlar uchun qat’iy tenglikdan foydalanadigan tasdiqlar uchun qat’iy rejimni taqdim etadi.

Ko‘proq bashorat qilinadigan natijalar uchun qat’iy rejimdan foydalanish tavsiya etiladi.

// Import the strict version of assert
const assert = require('assert').strict;

// These are equivalent
assert.strictEqual(1, 1);
assert.equal(1, 1); // In strict mode, this is the same as strictEqual

// These are equivalent
assert.deepStrictEqual({ a: 1 }, { a: 1 });
assert.deepEqual({ a: 1 }, { a: 1 }); // In strict mode, this is the same as deepStrictEqual

try {
  // This will throw an error in strict mode
  assert.equal('1', 1);
} catch (err) {
  console.error(`Error: ${err.message}`);
}
Misolni ishga tushirish »

Node.js Assert va Testing Framework-dan qachon foydalanish kerak

Node.js Assertdan foydalaning:

  • Oddiy skriptlarni yoki kichik yordamchi dasturlarni yozish
  • Rivojlanish jarayonida tezkor testlarni yaratish
  • Siz tashqi qaramlikdan qochishni xohlaysiz
  • Ichki Node.js modullarini qurish

Sinov tizimidan foydalaning (Jest, Mocha va boshqalar). Qachon:

  • Kattaroq loyihalar ustida ishlash
  • Sizga test runners, reporters va mock (soxtalashtirish) kabi xususiyatlar kerak
  • Keng qamrovli sinovni talab qiladigan ilovalarni yaratish
  • Xatolar haqida hisobot berish va sinovni yaxshiroq tashkil qilish kerak

Ilovalarni jiddiy sinovdan o‘tkazish uchun Node.js v18 da taqdim etilgan o‘rnatilgan Node.js Test Runner yoki Jest, Mocha yoki AVA kabi maxsus test tizimidan foydalaning.



W3Schools Pathfinder

Yutuqlaringizni kuzating – bu bepul!