0Pricing
Node.js Backend Development Bootcamp · บทเรียน

การจำลองและวัตถุแทนการทดสอบใน Node.js

เรียนรู้การแยกโค้ดที่กำลังทดสอบออกจากส่วนอื่น โดยแทนที่การพึ่งพาจริงด้วยม็อก สตับ และสปาย เพื่อให้การทดสอบหน่วยรวดเร็วและให้ผลแน่นอน

การจำลองและวัตถุแทนการทดสอบใน Node.js เป็นบทเรียน Node.js Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Node.js Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

The Problem with Real Dependencies

A unit test should check one piece of logic in isolation. But real code calls databases, APIs, the clock, and the file system — all slow, flaky, and unpredictable.

Test doubles replace those dependencies with controllable fakes.

Types of Test Doubles

Common terms you will hear:

  • Stub: returns a canned value
  • Spy: records how it was called
  • Mock: a stub + spy with built-in expectations
  • Fake: a lightweight working implementation

Creating a Mock Function

In Jest, jest.fn() creates a mock function. It records every call and lets you assert on them later.

const callback = jest.fn();
callback('hello');
expect(callback).toHaveBeenCalledWith('hello');

Defining Return Values

Tell a mock what to return with mockReturnValue, or for async code use mockResolvedValue to resolve a promise.

const getUser = jest.fn().mockResolvedValue({ id: 1, name: 'Ada' });
const user = await getUser();
expect(user.name).toBe('Ada');

Asserting on Calls

Spies let you verify interactions:

  • toHaveBeenCalled()
  • toHaveBeenCalledTimes(n)
  • toHaveBeenCalledWith(args)
const save = jest.fn();
save({ id: 1 });
expect(save).toHaveBeenCalledTimes(1);

Mocking a Module

To replace an entire imported module, use jest.mock(). Every export becomes an auto-mock you can configure per test.

jest.mock('./mailer');
const mailer = require('./mailer');
mailer.send.mockResolvedValue(true);

Spying on Existing Methods

Sometimes you want to watch a real method without replacing it. jest.spyOn() wraps an existing method so you can assert and optionally override it.

const spy = jest.spyOn(console, 'log');
console.log('hi');
expect(spy).toHaveBeenCalledWith('hi');

Resetting Between Tests

Mocks accumulate state. Reset them between tests so calls from one test do not leak into another.

  • mockClear() clears call data
  • mockReset() also clears implementations
afterEach(() => {
  jest.clearAllMocks();
});

Mocking Time

Tests that depend on the current time are flaky. Jest fake timers let you control the clock so timeouts and dates are deterministic.

jest.useFakeTimers();
const fn = jest.fn();
setTimeout(fn, 1000);
jest.advanceTimersByTime(1000);
expect(fn).toHaveBeenCalled();

Dependency Injection Makes Mocking Easy

Code that receives its dependencies as arguments is far easier to test than code that imports them directly. Design for testability.

function createService(db) {
  return { getUser: id => db.find(id) };
}
const fakeDb = { find: jest.fn().mockReturnValue({ id: 1 }) };
const svc = createService(fakeDb);

Don't Over-Mock

Mocking too much produces tests that only confirm your mocks were called — not that the code works. Mock external boundaries (DB, network), but test real logic directly when you can.

Quick Check

Test your understanding of test doubles.

Recap

You learned to isolate code with test doubles:

  • Create mocks with jest.fn() and configure return values
  • Replace modules with jest.mock()
  • Watch real methods with jest.spyOn()
  • Reset mocks between tests and control time with fake timers
  • Inject dependencies for testability and avoid over-mocking

Good mocking keeps unit tests fast, reliable, and focused.

คำถามที่พบบ่อย

บทเรียน “การจำลองและวัตถุแทนการทดสอบใน Node.js” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การจำลองและวัตถุแทนการทดสอบใน Node.js” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Node.js Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การจำลองและวัตถุแทนการทดสอบใน Node.js”

เรียนรู้การแยกโค้ดที่กำลังทดสอบออกจากส่วนอื่น โดยแทนที่การพึ่งพาจริงด้วยม็อก สตับ และสปาย เพื่อให้การทดสอบหน่วยรวดเร็วและให้ผลแน่นอน คุณปฏิบัติ Node.js Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Node.js Backend Development Bootcamp หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Node.js Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน

บทเรียน “การจำลองและวัตถุแทนการทดสอบใน Node.js” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Node.js Backend Development Bootcamp นี้ได้ไหม

ได้ บทเรียน Node.js Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การทดสอบหน่วยด้วย Jest
  2. การทดสอบการเชื่อมต่อปลายทาง API
  3. เทคนิคการแก้ไขข้อบกพร่องอย่างมีประสิทธิภาพ
  4. การจำลองและวัตถุแทนการทดสอบใน Node.js
← กลับไปที่ Node.js Backend Development Bootcamp