Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 55 ยท Shopify Functions

Testing and Debugging Functions

Test Shopify Functions with fixture inputs, the function run and replay commands, unit tests for pure logic, and a close watch on instruction and size limits.

A Shopify Function has no screen and no server log you can tail in production. It runs inside Shopify's sandbox during checkout, and when it misbehaves the buyer simply sees a missing discount, a hidden shipping option or an unexpected error. So you need a testing habit that does not depend on clicking through a real checkout every time.

The good news is that functions are built for testing. A function is a pure transformation from an input JSON document to an output JSON document, so you can test it at three levels: unit tests of your own logic, runs of the whole function against fixture files, and replays of real runs captured while your app is in development. This lesson walks through all three. The CLI commands and project files shown are read-only here, because they need the Shopify CLI and a store. The runnable examples are stand-ins: a tiny test harness, and a "function run" that checks the limits. For the function basics, see Building a Function from Scratch.

Level 1: unit tests for pure logic

Keep the interesting logic in plain functions that take plain data and return plain data, and keep the entry point thin. Then you can test the logic with any test runner, with no Shopify tooling at all. Generated JavaScript function projects come with a test setup (check your template for the exact runner and file names), and the idea is always the same:

JavaScript
// src/run.js (read-only sketch)
import { tierPercent } from "./tiers.js";

export function run(input) {
  const quantity = input.cart.lines.reduce((n, l) => n + l.quantity, 0);
  const percent = tierPercent(quantity);
  if (percent === 0) {
    return { operations: [] };
  }
  // ... build a discount operation
}
JavaScript
// src/run.test.js (read-only sketch)
import { describe, it, expect } from "vitest";
import { run } from "./run.js";

describe("run", () => {
  it("returns no operations for a small cart", () => {
    const input = { cart: { lines: [{ quantity: 1 }] } };
    expect(run(input).operations).toEqual([]);
  });
});

Good habits for function unit tests:

  • Test the edges, not just the middle. Empty cart, one line, quantity exactly at a tier boundary, a missing optional field, a metafield that is null because the merchant has not configured the function yet.
  • Test the configuration parsing separately. Settings arrive as a JSON string in a metafield value. A bad string must not crash the run; decide what "unconfigured" means (usually: return no operations) and test it.
  • Money and rounding. Amounts in function inputs are strings such as "19.99". Convert carefully and test rounding, as described in Money as Integers.

Here is a runnable stand-in that includes a minimal test harness, so you can see the pattern without any test framework. The function under test is a small tiered discount.

Node.js Unit tests for a pure function

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 last test fails on purpose, so you can see what a failing report looks like.

Level 2: run the whole function with fixtures

Unit tests do not prove that your input.graphql query and your code agree. For that, run the real compiled function against a sample input. The Shopify CLI can do this (read-only commands, run inside your app folder):

Terminal
# build the Wasm module and run it against an input file
shopify app function run --path extensions/volume-discount --input input.json

# regenerate types after changing input.graphql
shopify app function typegen --path extensions/volume-discount

# download the input schema for the target API version
shopify app function schema --path extensions/volume-discount

Command names and flags have changed between CLI versions, so check shopify app function --help for your installed version. The workflow is stable: keep a few input.json fixture files (a typical cart, an empty cart, an edge case), run the function, and compare the output with what you expect. The typegen step is worth running often: it turns your GraphQL query into types, so a renamed field is a compile error in your editor instead of a runtime surprise.

If you keep fixtures under version control, you can write a test that loads each fixture and checks the output. That is the cheapest end-to-end test you will have.

Level 3: replay real runs

While shopify app dev is running, your function executes for real in the development store's checkout, and each run is logged. You can then replay a logged run on your machine with the same input, which lets you debug a real case without recreating the cart (read-only):

Terminal
# list and replay recent runs of the function
shopify app function replay --path extensions/volume-discount

The replay picks a recorded run (the CLI asks which one) and executes your local code against the recorded input. This is the best answer to "it worked in my fixture, why not at checkout?": usually the real input has a field you did not expect, such as a null variant, a different currency, or a line with a gift card.

For output you want to read, use console.log (or eprintln! in Rust) inside the function. Messages go to the function's log stream, and you can view them while developing with shopify app logs or in the dev terminal. Logs are limited in size and are for development, so remove noisy logging before release.

Limits to watch

Functions run inside a strict budget, and exceeding it makes a run fail, which Shopify treats as "no result" rather than waiting. Documented limits include about 11 million WebAssembly instructions per run, a module size of about 256 KB, and caps on input and output size (read the current numbers in the reference, because they are adjusted from time to time). The function run output reports the instruction count of the run, which is how you notice a slow rule early.

What usually blows the budget:

  • Nested loops over all lines times all discounts or all options. Index data once with a Map.
  • Huge input queries, for example asking for every tag on every product when you need one.
  • Heavy JavaScript libraries that bloat the module. Prefer small helper code, or write the function in Rust, which compiles to a smaller and faster module.

The next stand-in imitates function run: it takes fixtures, counts "steps" (a rough stand-in for instructions) and checks them against a budget. The numbers are tiny and invented, but the workflow, a fixture in and a verdict out, is the real one.

Node.js A function run with a budget

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 debugging checklist

When a function does nothing in the real checkout:

  1. Is the function activated? A discount or customization needs a created record (a discount, validationCreate, deliveryCustomizationCreate, and so on), not just a deployed extension.
  2. Does the input contain what you assumed? Replay the real run.
  3. Is the configuration metafield present and valid JSON? Unconfigured is the most common cause.
  4. Did the run hit a limit? Check the run report for instruction counts and errors.
  5. Is the API version in the function's TOML the one whose output shape you wrote against? Output formats change between versions.
  6. Did you deploy the latest version (shopify app deploy), and is that version released? A local change is invisible to a store until then (see Deploying Your App).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why are Shopify Functions easy to unit test?

    A function reads an input document and returns an output document. With no side effects, a test only has to compare the output with the expected value.
  2. 2. What is the most useful reason to replay a logged run?

    Replay runs your local code against a recorded real input, so you can reproduce a checkout problem without rebuilding the cart.
  3. 3. A function works with your fixture but does nothing in the dev store. Which cause is common?

    A deployed extension alone does nothing. The store needs a discount, validation or customization record that points at it.
  4. 4. Which change helps most when a function exceeds its instruction budget?

    Indexing data once turns work proportional to lines times rules into work proportional to lines plus rules, and a smaller query and module help too.

Summary

  • Test functions at three levels: unit tests of pure logic, whole-function runs with fixture inputs, and replays of real runs.
  • Keep logic in plain functions and the entry point thin; always test unconfigured and malformed settings.
  • Use the CLI's function run, typegen, schema and replay commands; check --help because flags change between versions.
  • Watch the instruction and module-size limits; index data with a Map and keep the input query small.
  • When nothing happens at checkout, check activation, input, configuration, limits, API version and deployment, in that order.

Next: App Pricing Models and Billing Options.