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

การทดสอบหน่วยด้วย Jest

เรียนรู้การเขียนการทดสอบหน่วยแบบแยกอิสระสำหรับฟังก์ชันและโมดูลแต่ละรายการ โดยใช้กรอบงานการทดสอบ Jest

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

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

What is Unit Testing?

Welcome to unit testing! This is a fundamental practice in software development where individual components or functions of your application are tested in isolation.

Think of it like checking each gear in a clock separately to ensure it works perfectly before assembling the whole mechanism. This helps catch bugs early!

Meet Jest: Your Testing Buddy

For Node.js, Jest is one of the most popular and developer-friendly testing frameworks. It's developed by Facebook and offers a complete, integrated solution for JavaScript testing.

  • Zero Config: Often works out of the box.
  • Fast: Designed for performance.
  • Rich API: Powerful assertion library (matchers) included.
  • Snapshot Testing: Great for UI components.

Installing Jest

Getting started with Jest is easy. You'll install it as a development dependency in your Node.js project. Open your terminal in your project's root directory and run:

npm install --save-dev jest

After installation, you can add a script to your package.json file to easily run your tests:

"scripts": { "test": "jest" }

Our First Function to Test

Let's write a simple function that we want to test. This function will add two numbers. We'll put it in a file named sum.js.

You can run this file directly to see the function in action, but later we'll use Jest to test it automatically!

function sum(a, b) {
  return a + b;
}

// This allows us to use 'sum' in other files
module.exports = sum;

// Optional: Run this part only if the file is executed directly
if (require.main === module) {
  console.log("Running sum(2, 3):");
  console.log("Result: ", sum(2, 3)); // Expected: 5
}

Structuring Your Test File

Jest looks for test files with specific naming conventions, usually .test.js or .spec.js. Let's create sum.test.js in the same directory.

Inside, we use describe() to group related tests and test() (or it()) for individual test cases. This makes your tests organized and readable.

Making Assertions with Matchers

Inside a test() block, we use expect() combined with a "matcher" to assert that a value meets certain conditions. For example, .toBe() checks for exact equality.

Here's how we'd test our sum function:

const sum = require('./sum');

describe('sum function', () => {
  test('adds 1 + 2 to equal 3', () => {
    expect(sum(1, 2)).toBe(3);
  });

  test('adds 0 + 0 to equal 0', () => {
    expect(sum(0, 0)).toBe(0);
  });

  test('adds negative numbers correctly', () => {
    expect(sum(-1, -2)).toBe(-3);
  });
});

Running Your Tests

Now that you have your sum.js and sum.test.js files, and Jest installed with the script configured, you can run your tests!

Simply type npm test in your terminal. Jest will find your .test.js files, execute them, and report the results. You'll see green if all tests pass!

Handling Async Tests

Many Node.js applications deal with asynchronous operations (like fetching data, database calls). Jest handles these beautifully!

You can use async/await directly in your test functions. Jest will wait for the promise to resolve before completing the test.

function fetchData() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("Data from API");
    }, 50);
  });
}

module.exports = fetchData;

// Optional: Run this part only if the file is executed directly
if (require.main === module) {
  console.log("Simulating data fetch...");
  fetchData().then(data => console.log("Received: ", data));
}

Writing Async Tests

To test our fetchData function, we'll mark our test function as async. Jest also provides special matchers like .resolves and .rejects for promises.

Using await within your test makes asynchronous code look synchronous, improving readability.

const fetchData = require('./fetchData');

describe('fetchData function', () => {
  test('should return "Data from API"', async () => {
    const data = await fetchData();
    expect(data).toBe('Data from API');
  });

  test('should resolve with specific data', () => {
    return expect(fetchData()).resolves.toBe('Data from API');
  });
});

Jest Matcher Check

Which of the following Jest matchers would you use to check if two objects have the same value (deep comparison), not just if they are the same instance?

Unit Testing with Jest: Recap

Great job! You've learned the basics of unit testing with Jest. We covered:

  • What unit testing is and its benefits.
  • How to install and set up Jest.
  • Structuring tests with describe and test.
  • Making assertions using expect and matchers like .toBe() and .toEqual().
  • Handling asynchronous code with async/await.

Keep practicing and happy testing!

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

บทเรียน “การทดสอบหน่วยด้วย Jest” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “การทดสอบหน่วยด้วย Jest”

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

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

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

บทเรียน “การทดสอบหน่วยด้วย Jest” ใช้เวลานานแค่ไหน

บทเรียน 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