Aug 19, 2024
5
min. Reading Time

Setting Up Integration Testing for Shopify Theme App Extensions Using Playwright

Setting Up Integration Testing for Shopify Theme App Extensions Using Playwright

Setting Up Integration Testing for Shopify Theme App Extensions Using Playwright

Zakaria @ Beehive Apps

Shopify App Developer

Shopify theme app extension integration testing
Shopify theme app extension integration testing
Shopify theme app extension integration testing

When developing a Shopify Theme App Extension (TAX), ensuring that it integrates seamlessly with the Shopify environment is crucial. One of the best ways to verify this is through integration testing. In this guide, we’ll walk you through setting up integration testing using Playwright, a powerful tool that automates browser testing and simulates user interactions.

Prerequisites

Before we dive in, we assume you’ve already created and set up your Shopify Theme App Extension (TAX). If not, complete that step first. We’ll also assume you have the following tools and knowledge:

Step 1: Setting Up Your Development Environment

To get started, you need to spin up the local server of your app. This can be done using the following command:

shopify app dev --theme-app-extension-port=3001

This command will start a preview server of your TAX, making it accessible at http://127.0.0.1:3001. Before running your tests, make sure to activate the TAX in the host theme. Here's a screenshot to guide you through this process:

Step 2: Installing Playwright

First, ensure Playwright is installed and initialized in your project. You can do this by running:

npm init playwright

Playwright supports testing across multiple browsers, including Chromium, Firefox, and WebKit, making it a versatile choice for integration testing, but I have only tested this setup using Chromium, so feel free to play around with it and try other browsers as well.

Step 3: Configuring Playwright for Shopify Theme Testing

Next, let’s configure Playwright to work with your Shopify TAX. Create a Playwright configuration file (playwright.config.ts) in the root of your project and configure it as follows:

import { defineConfig, devices } from "@playwright/test";

/**
 * Read environment variables from file.
 * https://github.com/motdotla/dotenv
 */
// import dotenv from 'dotenv';
// dotenv.config({ path: path.resolve(__dirname, '.env') });

export const STORAGE_FILE = "playwright/tmp/shopifyState.json";
const SETUP_TEST_NAME = "setup";

/**
 * See https://playwright.dev/docs/test-configuration.
 */
export default defineConfig({
  testDir: "./tests", /* Change this to suit your project's structure */
  /* Run tests in files in parallel */
  fullyParallel: true,
  /* Fail the build on CI if you accidentally left test.only in the source code. */
  forbidOnly: true,
  /* Retry on CI only */
  retries: process.env.CI ? 2 : 0,
  /* Opt out of parallel tests on CI. */
  workers: process.env.CI ? 1 : undefined,
  /* Reporter to use. See https://playwright.dev/docs/test-reporters */
  reporter: [["html", { open: "never" }]],
  /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
  use: {
    /* Base URL to use in actions like `await page.goto('/')`. */
    baseURL: "http://127.0.0.1:3001",
    headless: true,
    /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
    trace: "on-first-retry",
  },

  /* Configure projects for major browsers */
  projects: [
    {
      name: SETUP_TEST_NAME,
      testMatch: /.*\.setup\.ts/,
      use: {
        // We add storageState to the setup test as well so that if our stored state is still valid, we can just use that and avoid inputting the password and all that.
        storageState: STORAGE_FILE,
      },
    },
    {
      name: "chromium",
      use: {
        ...devices["Desktop Chrome"],
        storageState: STORAGE_FILE,
      },
      dependencies: [SETUP_TEST_NAME],
    },
  ],
});

In this configuration:

  • Setup Project: The first project bypasses the Shopify password page and stores session cookies in a file (shopifyState.json). This file is then reused by the subsequent tests to ensure a seamless flow.

  • Desktop Chrome Project: This project runs the actual tests using the session state set up in the previous project. The dependency should be added to all the projects besides the setup (duh). This way Playwright will first run the setup and only after it will run all the tests in parallel.

Make sure to also create the destination folder for our state by running the following commands:

mkdir -p playwright/tmp
echo $'\nplaywright/tmp' >> .gitignore

Step 4: Writing Your First Test

Let’s create a setup script to handle the password bypass and session storage. Create a file named tests/myTax.setup.js:

import { test as setup } from "@playwright/test";
import { STORAGE_FILE } from "playwright.config";

setup("Bypass storefront password page", async ({ page }) => {
  //It doesn't matter which page we go to here
  await page.goto("/");
  // Check if we are on the password page by checking the URL for /password
  const url = page.url();
  if (url.includes("/password")) {
    // Fill in the password and submit the form
    await page.fill('input[name="password"]', "your-password");
    await page.click('button[type="submit"]');

    // Wait for the page to load and then save the browser application state into our storage file
    await page.waitForEvent("load");

    await page.context().storageState({
      path: STORAGE_FILE,
    });
  }

  page.close();
});

Now, you can create a test file for your TAX, such as tests/myTax.spec.js:

// Importing the necessary functions from Playwright
import { test, expect } from "@playwright/test";

// Example test using ES6 modules
test("Basic interaction with the Shopify theme app extension", async ({
  page,
}) => {
  // Navigate to the local Shopify preview
  await page.goto("products/your-product"); // Replace with your target URL

  // Wait for the theme app extension to load
  await page.waitForSelector(".your-theme-app-extension-selector"); // Replace with your actual selector

  // Verify the theme app extension is present on the page
  const extensionElement = await page.$(".your-theme-app-extension-selector");
  expect(extensionElement).not.toBeNull();

  // Simulate a user interaction (e.g., clicking a button)
  await page.click(".your-interactive-element"); // Replace with your actual interactive element

  // Check the result of the interaction
  const resultText = await page.textContent(".result-element"); // Replace with your result element selector
  expect(resultText).toBe("Expected Text"); // Replace with your expected result
});

Step 5: Running the Tests

With everything set up, you can now run your tests using Playwright’s CLI:

npx playwright test

Playwright will first run the setup project to bypass the password and save the session state. Then, it will proceed to run the tests using the stored session.

Conclusion

By following these steps, you’ve set up integration testing for your Shopify Theme App Extension using Playwright. With automated testing in place, you can ensure your extension integrates seamlessly with the Shopify environment, catching issues before they reach production.

Now that you’ve got the basics down, consider exploring more advanced features of Playwright, such as parallel testing and cross-browser testing, to further enhance your testing strategy.

Additional Resources

Other articles you might like

Other articles you might like

© 2024 Beehive Apps. All rights reserved

© 2024 Beehive Apps. All rights reserved

© 2024 Beehive Apps. All rights reserved