اختبار الوحدات باستخدام Spectron
تعلّم كتابة اختبارات وحدات فعّالة لتطبيقات Electron باستخدام Spectron، وهو إطار مصمم خصيصًا لاختبار Electron
اختبار الوحدات باستخدام Spectron درس مجاني في Electron Desktop App Development على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Electron Desktop App Development، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Electron Desktop App Development 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Why Unit Test Electron Apps?
Building desktop applications with Electron brings the power of web technologies to your users' desktops. Just like any software, these apps need to be reliable and bug-free.
Unit testing helps ensure individual components of your application work as expected. For Electron, this means testing both the main (Node.js) and renderer (Chromium) processes, as well as their interactions.
Meet Spectron: Electron's Test Tool
Spectron is a testing framework specifically designed for Electron applications. It's built on top of WebDriver (like ChromeDriver), allowing you to programmatically control an Electron app just like a user would.
- It launches your Electron app in a separate process.
- It provides APIs to interact with both the main and renderer processes.
- You can simulate user actions like clicks, typing, and navigation.
Spectron doesn't replace your test runner (like Mocha or Jest); it works with them!
Setting Up Your Test Environment
Before writing tests with Spectron, you'll need a few things:
- Node.js & npm: Already installed for Electron development.
- An Electron application: The app you want to test.
- A test runner: We'll use Mocha for its simplicity and wide adoption.
- An assertion library: Chai is a popular choice for making assertions.
These tools will help you structure your tests and verify outcomes.
Installing Spectron, Mocha, & Chai
Let's install the necessary packages as development dependencies using npm:
spectron: The Electron testing framework.mocha: Our test runner.chai: Our assertion library.
Run the following command in your project's root directory:
npm install --save-dev spectron mocha chaiBasic Spectron Test Structure
A typical Spectron test file uses Mocha's describe and it blocks. The key is to instantiate Spectron's Application class and manage its lifecycle with beforeEach and afterEach hooks.
This ensures your app starts before each test and stops afterwards.
const { Application } = require('spectron');
const path = require('path');
const assert = require('assert'); // Using Node's built-in assert for simplicity
describe('Application launch', function () {
this.timeout(10000); // Give Electron app time to start
let app;
beforeEach(async function () {
app = new Application({
path: path.join(__dirname, '..', 'node_modules', '.bin', 'electron'),
args: [path.join(__dirname, '..', 'main.js')], // Path to your app's main file
});
await app.start();
});
afterEach(async function () {
if (app && app.isRunning()) {
await app.stop();
}
});
it('shows an initial window', async function () {
const count = await app.client.getWindowHandles().then(handles => handles.length);
assert.strictEqual(count, 1);
});
});Interacting with the Renderer Process
Spectron's app.client object gives you access to the Chromium WebDriver API. This allows you to interact with the web content in your renderer process.
- Use CSS selectors to find elements.
- Get text content, attribute values, or check element visibility.
- Execute JavaScript directly within the renderer process.
It's like having browser developer tools in your test!
// Get text from an element with ID 'my-heading'
const headingText = await app.client.element('#my-heading').then(el => el.getText());
assert.strictEqual(headingText, 'Welcome!');
// Execute JavaScript to get the document title
const title = await app.client.webContents.executeJavaScript('document.title');
assert.strictEqual(title, 'My Electron App');Example: Verify Window Title
Let's write a complete test to ensure our Electron application's main window has the correct title after it launches. This verifies a basic aspect of your app's initialization.
const { Application } = require('spectron');
const path = require('path');
const assert = require('assert');
describe('Window Title Verification', function () {
this.timeout(10000);
let app;
beforeEach(async function () {
app = new Application({
path: path.join(__dirname, '..', 'node_modules', '.bin', 'electron'),
args: [path.join(__dirname, '..', 'main.js')],
});
await app.start();
});
afterEach(async function () {
if (app && app.isRunning()) {
await app.stop();
}
});
it('should have the title "My Electron App"', async function () {
const title = await app.client.webContents.getTitle();
assert.strictEqual(title, 'My Electron App');
});
});Simulating User Actions
Spectron allows you to mimic user interactions. This is crucial for testing interactive elements and user flows within your application.
click(selector): Simulates a click on an element.setValue(selector, value): Types text into an input field.
You can then assert the resulting state of your UI or data.
// Assuming an HTML button with ID 'increment-btn'
// and a display element with ID 'counter-display'
await app.client.click('#increment-btn');
const counterValue = await app.client.getText('#counter-display');
assert.strictEqual(counterValue, '1');
// Assuming an input field with ID 'username-input'
await app.client.setValue('#username-input', 'testuser');
const username = await app.client.getValue('#username-input');
assert.strictEqual(username, 'testuser');Accessing the Main Process
Spectron also provides ways to interact with the main process, which is where your Node.js code runs. This is powerful for testing backend logic or Electron's native APIs.
app.client.electron: Accesses Electron's built-in modules (e.g.,app,dialog).app.client.mainProcess: Allows calling functions directly on the main process's global object.
Remember, for security, direct access is often limited by context isolation and preload scripts.
// Get the Electron app version from the main process
const version = await app.client.electron.app.getVersion();
console.log(`Electron App Version: ${version}`);
// Example: Call a custom function exposed by the main process
// (Requires 'main.js' to expose 'myCustomFunction' globally or via contextBridge)
// const mainProcessResult = await app.client.mainProcess.myCustomFunction('data');
// assert.strictEqual(mainProcessResult, 'processed-data');Spectron Quick Check
Let's test your understanding of Spectron's capabilities!
Recap: Unit Testing with Spectron
In this lesson, you learned how Spectron helps you unit test your Electron applications effectively.
- Spectron uses WebDriver to launch and control your Electron app.
- It allows you to interact with both the renderer process (UI elements, JS execution) and the main process (Electron APIs, Node.js functions).
- Combined with test runners like Mocha and assertion libraries like Chai, Spectron provides a robust way to ensure your Electron app behaves as expected.
Keep practicing to build reliable desktop experiences!
الأسئلة الشائعة
هل درس «اختبار الوحدات باستخدام Spectron» مجاني؟
نعم — نص درس «اختبار الوحدات باستخدام Spectron» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Electron Desktop App Development، انتقل إلى CoddyKit PRO. تتضمن دورة Electron Desktop App Development 4 دروس في المجموع.
ماذا ستتعلم في «اختبار الوحدات باستخدام Spectron»؟
تعلّم كتابة اختبارات وحدات فعّالة لتطبيقات Electron باستخدام Spectron، وهو إطار مصمم خصيصًا لاختبار Electron تتمرن على Electron Desktop App Development مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Electron Desktop App Development؟
لا تُشترط خبرة سابقة. Electron Desktop App Development على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.
كم من الوقت يستغرق درس «اختبار الوحدات باستخدام Spectron»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Electron Desktop App Development هذا؟
نعم. كل درس في Electron Desktop App Development يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- تصحيح أخطاء العمليات الرئيسية وعمليات العرض
- اختبار الوحدات باستخدام Spectron
- سير عمل الاختبار الشامل
- اختبار E2E حديث باستخدام Playwright