Skip to content

أنشئ المحاكاة باستخدام دالة mock من bun:test.

ts
import { test, expect, mock } from "bun:test";

const random = mock(() => Math.random());

يمكن لدالة المحاكاة قبول وسيطات.

ts
import { test, expect, mock } from "bun:test";

const random = mock((multiplier: number) => multiplier * Math.random());

نتيجة mock() هي دالة جديدة تم تزيينها ببعض الخصائص الإضافية.

ts
import { mock } from "bun:test";

const random = mock((multiplier: number) => multiplier * Math.random());

random(2);
random(10);

random.mock.calls;
// [[ 2 ], [ 10 ]]

random.mock.results;
//  [
//    { type: "return", value: 0.6533907460954099 },
//    { type: "return", value: 0.6452713933037312 }
//  ]

تجعل هذه الخصائص الإضافية من الممكن كتابة تأكيدات expect حول استخدام دالة المحاكاة، بما في ذلك عدد المرات التي تم فيها استدعاؤها، والوسيطات، وقيم الإرجاع.

ts
import { test, expect, mock } from "bun:test";

const random = mock((multiplier: number) => multiplier * Math.random());

test("random", async () => {
  const a = random(1);
  const b = random(2);
  const c = random(3);

  expect(random).toHaveBeenCalled();
  expect(random).toHaveBeenCalledTimes(3);
  expect(random.mock.args).toEqual([[1], [2], [3]]);
  expect(random.mock.results[0]).toEqual({ type: "return", value: a });
});

راجع الوثائق > مُشغل الاختبارات > المحاكاة للحصول على الوثائق الكاملة للمحاكاة مع مُشغل اختبارات Bun.

Bun بواسطة www.bunjs.com.cn تحرير