0Pricing
Browser Extensions Development (Chrome & Edge) · บทเรียน

การเขียนการทดสอบหน่วยสำหรับส่วนขยาย

สร้างการทดสอบหน่วยสำหรับตรรกะของส่วนขยายโดยใช้กรอบงานการทดสอบ JavaScript ยอดนิยม เพื่อให้มั่นใจถึงความน่าเชื่อถือ

การเขียนการทดสอบหน่วยสำหรับส่วนขยาย เป็นบทเรียน Browser Extensions Development (Chrome & Edge) ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Browser Extensions Development (Chrome & Edge) และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Browser Extensions Development (Chrome & Edge) มีบทเรียนทั้งหมด 4 บทเรียน

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

Intro to Unit Testing

Welcome! In this lesson, we'll dive into unit testing for browser extensions. Unit testing is a way to test small, isolated parts of your code, often called "units."

For extensions, this means testing individual functions or modules without needing to run the full browser environment. It's about ensuring each piece works correctly on its own.

Why Test Extensions?

Testing is crucial for building robust browser extensions. Here's why:

  • Reliability: Catches bugs early, ensuring your extension works as expected.
  • Maintainability: Makes future changes safer, preventing accidental breakage (regressions).
  • API Changes: Helps adapt to updates in browser APIs (like Manifest V3 changes).
  • Complex Logic: Ensures tricky background or content script logic is sound.

Pick Your Test Framework

Several JavaScript frameworks help you write and run tests. Popular choices include:

  • Jest: A complete testing solution from Facebook, known for its ease of use and built-in mocking.
  • Mocha: A flexible test runner, often paired with an assertion library like Chai.
  • Vitest: A fast, modern alternative built on Vite.

For this lesson, we'll use Jest due to its popularity and comprehensive features.

Set Up Jest for Testing

To get started, create a project folder and initialize it with npm. Then, install Jest as a development dependency:

npm init -y npm install --save-dev jest

Next, add a test script to your package.json file so you can easily run tests:

{
  "name": "my-extension-tests",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "jest": "^29.0.0" // Version may vary
  }
}

Test Pure JavaScript Logic

Let's write a simple utility function that might be part of your extension's logic. Create a file named utils.js:

// utils.js
function sum(a, b) {
  return a + b;
}

function capitalize(str) {
  if (!str) return '';
  return str.charAt(0).toUpperCase() + str.slice(1);
}

module.exports = { sum, capitalize };

Writing Your First Test

Now, create a test file named utils.test.js. Jest automatically finds files ending with .test.js or .spec.js.

We'll import our functions and use Jest's test (or it) and expect syntax to define and check our tests. Try running this example!

// utils.test.js
const { sum, capitalize } = require('./utils');

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

test('capitalizes a string', () => {
  expect(capitalize('hello')).toBe('Hello');
  expect(capitalize('world')).toBe('World');
  expect(capitalize('')).toBe('');
});

// To run these tests, execute: npm test

The Challenge of Chrome APIs

Browser extensions rely heavily on the chrome.* APIs (e.g., chrome.storage, chrome.tabs). These APIs are only available within a browser environment.

When running unit tests outside a browser (like with Node.js-based Jest), the chrome object will be undefined. To test logic that uses these APIs, we need to mock them.

Mocking means creating a simulated version of an object or function to control its behavior during a test.

Mocking chrome.storage

Let's create a utility that uses chrome.storage.local. This function would typically be in your background script or another module.

First, our utility function (e.g., in storageUtils.js):

// storageUtils.js
async function saveSetting(key, value) {
  if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
    await chrome.storage.local.set({ [key]: value });
    return true;
  }
  // Fallback for non-browser environments or missing API
  console.warn('chrome.storage.local not available');
  return false;
}

async function getSetting(key) {
  if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
    const result = await chrome.storage.local.get(key);
    return result[key];
  }
  // Fallback
  console.warn('chrome.storage.local not available');
  return undefined;
}

module.exports = { saveSetting, getSetting };

Testing with Mocked APIs

Now, let's write a test for our storageUtils.js. We'll create a mock for chrome.storage.local before each test to simulate its behavior.

Jest's jest.fn() is perfect for creating mock functions and tracking their calls. Try running this test!

// storageUtils.test.js
const { saveSetting, getSetting } = require('./storageUtils');

// Mock chrome.storage.local globally for tests
const mockStorage = {};
global.chrome = {
  storage: {
    local: {
      set: jest.fn(async (obj) => {
        Object.assign(mockStorage, obj);
        return Promise.resolve();
      }),
      get: jest.fn(async (key) => {
        return Promise.resolve({ [key]: mockStorage[key] });
      }),
    },
  },
};

beforeEach(() => {
  // Reset mock storage and clear Jest mock calls before each test
  for (const key in mockStorage) { delete mockStorage[key]; }
  chrome.storage.local.set.mockClear();
  chrome.storage.local.get.mockClear();
});

test('saveSetting saves data to chrome.storage.local', async () => {
  await saveSetting('username', 'CoddyKit');
  expect(chrome.storage.local.set).toHaveBeenCalledWith({ username: 'CoddyKit' });
  expect(mockStorage.username).toBe('CoddyKit');
});

test('getSetting retrieves data from chrome.storage.local', async () => {
  mockStorage.username = 'CoddyKit'; // Pre-set mock storage
  const username = await getSetting('username');
  expect(chrome.storage.local.get).toHaveBeenCalledWith('username');
  expect(username).toBe('CoddyKit');
});

// To run these tests, execute: npm test

Quick Check: Unit Testing

You've learned about unit testing and how to mock browser APIs. Which of the following statements is TRUE about unit testing browser extension logic?

Recap: Unit Testing

In this lesson, you learned:

  • The importance of unit testing for browser extensions.
  • How to set up a testing environment using Jest.
  • How to write unit tests for pure JavaScript functions.
  • The concept and practice of mocking chrome.* APIs to test extension logic outside the browser.

Unit testing is a critical skill for building robust and maintainable extensions. Keep practicing to ensure your extension's core logic is always solid!

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

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

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

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

สร้างการทดสอบหน่วยสำหรับตรรกะของส่วนขยายโดยใช้กรอบงานการทดสอบ JavaScript ยอดนิยม เพื่อให้มั่นใจถึงความน่าเชื่อถือ คุณปฏิบัติ Browser Extensions Development (Chrome & Edge) ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Browser Extensions Development (Chrome & Edge) หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Browser Extensions Development (Chrome & Edge) บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

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

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

ฉันเขียนและรันโค้ดในบทเรียน Browser Extensions Development (Chrome & Edge) นี้ได้ไหม

ได้ บทเรียน Browser Extensions Development (Chrome & Edge) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

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

  1. การแก้ไขข้อบกพร่องของส่วนประกอบส่วนขยาย
  2. การเขียนการทดสอบหน่วยสำหรับส่วนขยาย
  3. กลยุทธ์การเพิ่มประสิทธิภาพ
  4. การบันทึก การรายงานข้อผิดพลาด และการวินิจฉัย
← กลับไปที่ Browser Extensions Development (Chrome & Edge)