微前端架構下的測試策略 (Testing Strategy in Micro Frontend Architecture)

在微前端的架構之下,為了確保其內包含的應用程式能正常運作,這就需要我們在微前端的架構下進行測試。

選擇哪一種測試類型?

微前端底下測試其應用程式是否能正常運作,要選用「端對端測試」(end-to-end testing) 來進行測試。

原因是單元測試 (unit testing) 和整合測試 (integration testing) 的範圍太小,只能涵蓋單一應用程式的功能,而無法涵蓋微前端的應用程式的所有功能。舉例來說,在微前端的架構下,外殼 A repo 之內的 unit testing 只能測到外殼 A repo 的功能,無法測試到外殼 A repo 和應用程式 B 的整合是否正常運作;而前端世界中提到的 integration testing,通常是指元件之間的整合測試,同樣的也無法涵蓋微前端的應用程式的所有功能。 因此,若想測試外殼 A 是否能與應用程式 B 正常運作,就必須使用 end-to-end testing 來進行測試。

選擇哪一種測試工具?

能做 end-to-end testing 的框架都能選為測試工具,像是 Cypress、Playwright、Puppeteer 等。

該怎麼規劃測試策略?測試的範圍是什麼?

由於想要測試的是外殼 A 是否能與應用程式 B 正常運作,因此測試的重點為 A 是否能正常載入 B 的內容,並且能正常與 B 的內容互動。至於 B 的內容是否正確,就不在考慮範圍之內。

測試範例

以下是測試外殼 A 是否能正常載入應用程式 B 的測試範例,以 Playwright 實作。

點擊 A (MFE) 的 memu 的每個項目,確認相對應的 B (app) 頁面能正確載入。

test.describe(
  'Application B',
  () => {
    test('should load all the pages successfully through the menu entry', async ({ page }) => {
      // Locate the navigation menu and application content area
      const menuSelector = 'menu';
      const menuItemSelector = 'menuItem';
      const appContentSelector = 'appContent';

      // Verify that the navigation menu is visible
      const menu = page.getByTestId(menuSelector);
      await expect(menu).toBeVisible();

      // Retrieve all menu items from the navigation
      const menuItems = await menu.getByTestId(menuItemSelector);.all();
      expect(menuItems).not.toBeNull();

      // Confirm that each menu item's href matches the expected values
      for (const item of menuItems) {
        const href = await item.getAttribute('href');
        expect(MENU_ENTRIES.some((entry) => entry.url === href)).toBeTruthy();

        await item.click();
        await page.waitForURL(href);

        // Wait for the Micro Frontend (MFE) to load and validate that the corresponding content is displayed
        const appContent = page.getByTestId(appContentSelector);
        await expect(appContent).toBeVisible();
      }
    });
  },
);

Micro Frontends 微前端 End-to-End Testing 端對端測試 Playwright 自動化測試 front-end architecture front end testing