Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 55 ยท Testing, Deployment and Operations

Testing Shopify Apps

Test a Shopify app with confidence: unit tests with a mocked admin client, signed webhook tests, factories, development stores and test charges, with runnable stand-ins.

A Shopify app is a program that depends on a platform you do not control. Your code calls the Admin API, receives webhooks, and runs inside an iframe in someone else's admin. That makes it tempting to test only by clicking around a development store. Clicking is useful, but it is slow, it does not repeat exactly, and it tells you nothing when you refactor.

The good news is that most of your logic can be tested without Shopify at all. The trick is to keep a thin edge that talks to Shopify and a core that makes decisions, then replace the edge with a stub in tests. This lesson shows the layers of testing for an app, with runnable stand-ins for the parts that cannot run on this site. The webhook ideas build on Verifying Webhook Signatures and Reliable Webhook Handlers.

The real app code in this lesson (a React Router app generated by the CLI, tested with a runner such as Vitest) is shown read-only, because the site cannot install npm packages. The runnable examples use plain Node with a tiny test helper, so you can see the technique without a framework.

The testing layers

flowchart TB
    A["Unit tests<br/>pure logic, no network"] --> B["Handler tests<br/>stubbed admin client, signed webhooks"]
    B --> C["Dev store checks<br/>real API, real install"]
    C --> D["Pre-release run<br/>test charges, fresh store"]

Cheap and fast tests at the bottom of the pyramid, slow and realistic checks at the top. Run the lower layers constantly.

  • Unit tests cover pure functions: tag rules, discount math, plan limits. They need no mocks.
  • Handler tests call a route action or webhook handler with a fake admin object and fake request, then assert on what the handler asked Shopify to do.
  • Development store checks exercise the real API, the real install and the real iframe.
  • Pre-release runs use a clean store and test charges, as reviewers will (see App Store Requirements and Review).

Design for testing: pass the client in

In the app template, route code receives an admin object from authenticate.admin(request). Its graphql method sends a query and returns a response whose json() yields { data, errors, extensions }. If your business logic takes that admin object as a parameter, a test can hand in a stub.

A read-only sketch of the idea, using a Vitest-style runner:

TypeScript
// app/services/archive-drafts.server.ts
export async function archiveDraftProducts(admin: AdminClient) {
  const response = await admin.graphql(`#graphql
    query { products(first: 50, query: "status:draft") { nodes { id title } } }`);
  const { data } = await response.json();
  return data.products.nodes;
}

// app/services/archive-drafts.server.test.ts
import { test, expect, vi } from "vitest";

test("returns draft products", async () => {
  const admin = {
    graphql: vi.fn().mockResolvedValue({
      json: async () => ({ data: { products: { nodes: [{ id: "gid://shopify/Product/1", title: "Mug" }] } } }),
    }),
  };
  const result = await archiveDraftProducts(admin as any);
  expect(result).toHaveLength(1);
  expect(admin.graphql).toHaveBeenCalledTimes(1);
});

This block is read-only. The same idea works with any runner: the stub returns canned JSON, and the test asserts on the result and on how the stub was called. The next TryIt builds the stub by hand.

A stub GraphQL client you can run

A useful stub does more than return one fixed answer. It records every call (so tests can assert on the query and variables) and it can be told to fail. Here is a small one, together with a service that tags products, and three tests run by a mini test helper.

Node.js Testing a service with a stub GraphQL client

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The fourth test fails on purpose, so you can see what a useful failure message looks like. Change the expected value to true and all four pass. Notice that the stub throws on an unexpected extra request: tests that silently allow extra calls hide bugs such as loops that query once per product.

Testing webhook handlers

A webhook handler has two jobs that need separate tests: reject requests with a wrong signature, and process good ones exactly once. Your test builds the request the way Shopify does: raw body, then a base64 HMAC-SHA256 of that body with the app secret in the X-Shopify-Hmac-Sha256 header, plus a webhook ID header for deduplication. See Webhooks in Shopify for the header list and the generic ideas in Webhooks and Signature Verification.

Node.js Signed webhook tests with a factory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A factory like webhookRequest() is the most valuable test helper in a Shopify app. Every test starts from a valid request and overrides one thing, so each test shows exactly what makes it special. Build similar factories for products, orders and sessions. Never put real merchant data in them: keep fixtures small, invented and obviously fake.

Development stores and test charges

Stubs cannot tell you whether your query is valid against the real schema, whether your scopes are enough, or whether your embedded page renders. For that, use a development store (a free store created from your Partner or Dev Dashboard) with these habits:

  • Keep a few dev stores: a clean one for install tests, and one with realistic data (hundreds of products, a few orders) for performance and pagination.
  • Run shopify app dev and install the app on the store; edit and watch changes live. See Creating an App with the CLI.
  • Trigger webhooks for real by editing data in the admin. The CLI can also send sample webhook payloads to your local server for quick checks.
  • Test charges. When you create a subscription through the Billing API, pass the test flag so no real money moves. Development stores can only approve test charges anyway. Make the flag depend on the environment, never hard-code it, and write a test that production configuration sets it to false. See Implementing Billing with the Billing API.
  • Test uninstall and reinstall: the second install should not collide with data left from the first.
  • Test with the API version you ship. Reading API Versioning and Deprecations helps you schedule a test pass for each new version.

What to test, in order of value

  1. Pure business rules (rules, calculations, plan limits).
  2. Handlers' behavior on errors: userErrors, throttling, missing resources, and expired tokens.
  3. Webhook signature rejection and duplicate handling.
  4. Authorization boundaries: data for shop A must never be returned to shop B (see Databases and Session Storage in Production).
  5. A smoke test on a real dev store before every release.

Avoid testing the platform: you do not need a test that Shopify returns products. Test what your code does with the response.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is it useful to pass the admin client into your service functions instead of importing it inside them?

    Injecting the client keeps the Shopify edge thin. Tests can substitute a stub, so logic runs without a network, a store or a token.
  2. 2. A stub client is asked for a response but no handler is left. What should it do?

    Failing loudly exposes loops and accidental extra requests. A lenient stub would let those bugs pass unnoticed.
  3. 3. Which set of webhook tests is most complete?

    Rejection paths matter as much as the happy path, and duplicate deliveries are normal in practice, so they need their own test.
  4. 4. How should the test flag of a billing request be set?

    Hard-coding either value is risky: true in production means you never get paid, false in development may create real charges on the wrong account.
  5. 5. What can a development store check that stubbed unit tests cannot?

    Only the real API validates the schema, scopes, permissions and the embedded UI. That is why both kinds of tests are needed.

Summary

  • Keep a thin Shopify edge and a testable core; pass the admin client in so tests can stub it.
  • A good stub records calls, returns canned JSON and fails on unexpected requests.
  • Test webhooks with a factory that signs real HMACs, and cover wrong secret, missing header, tampering and duplicates.
  • Use development stores for the real API, install and UI, and set the billing test flag from the environment.
  • Test business rules first, then error handling, then authorization boundaries, then a smoke test before release.

Next: Databases and Session Storage in Production shows how to store your app's data safely per shop.