Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 28 ยท Quality and Production

Testing Apps and Themes

Test BigCommerce apps and themes with confidence: unit tests for webhook handlers, API mocking, Stencil theme checks, sandbox flows and contract tests.

Commerce code handles money, stock and customer data, and it runs inside someone else's platform. That combination makes mistakes expensive and hard to reproduce: you cannot easily ask the real store to fail on demand, and a bug found by a shopper is a bug found too late. A good test setup gives you fast checks on your own logic, safe stand-ins for the platform's API, and a few slow but valuable checks against a real sandbox store.

This lesson sorts tests into layers: unit tests for handlers and calculations, API mocking, theme checks for Stencil, sandbox flows, and contract tests that notice when an API stops looking the way you expect. The platform itself cannot run on this site, so the examples test a small webhook handler against a mock API using Node's built-in test runner, and a contract check against a fake response. For the general ideas, Webhooks and Signatures and Idempotency explain what a handler must do, and The Built-in Test Runner teaches the runner.

The testing pyramid for a BigCommerce project

Think of three layers, from many cheap tests to few expensive ones:

  1. Unit tests exercise your own functions with no network: price rounding, mapping a supplier feed to catalog fields, verifying a signature, deciding whether a webhook is a duplicate. They run in milliseconds and should make up most of your suite.
  2. Integration tests with a mocked API run your handler or client end to end against a fake of the BigCommerce API that you control. They prove that your code sends the right requests and copes with errors such as a 429 or a missing resource.
  3. Sandbox tests run against a real development store with real tokens. They are slow and shared, so keep them few: install the app, create a product, receive a webhook, load a theme preview. Run them before a release, not on every save.
flowchart TB
    S["Sandbox store tests<br/>(few, slow, real)"]
    I["Integration tests with mock API<br/>(some, fast)"]
    U["Unit tests<br/>(many, instant)"]
    U --> I --> S

More tests at the bottom, fewer at the top.

Design handlers so they can be tested

The best test advice is about design: make the handler a plain function that receives its dependencies. A handler that calls fetch against a hard-coded URL and reads global state is nearly impossible to test. A handler that receives an api object and a seen store is trivial.

JavaScript
// Hard to test (read-only):
export async function handle(event) {
  const res = await fetch(`https://api.bigcommerce.com/stores/${process.env.HASH}/v2/orders/${event.data.id}`, {
    headers: { 'X-Auth-Token': process.env.TOKEN },
  });
  // ...
}

// Easy to test (read-only):
export async function handle(event, { api, seen }) {
  const order = await api.getOrder(event.data.id);
  // ...
}

In production you pass an api object that wraps the real HTTP calls (with the token handling from API Accounts, Tokens and Scopes). In tests you pass a fake with the same methods that records calls and returns canned data. This is often called dependency injection, and it needs no library.

Mocking the API honestly

A mock is only useful if it behaves like the real thing in the ways that matter. Give your fake the failure modes you must handle: not found, a rate-limit response, a slow response, malformed data. Also record every call, so a test can assert that the handler fetched an order once and did not fetch it for a duplicate event. Keep mock data small and named after the scenario ("order with two items", "refunded order").

For HTTP-level code, Node's fetch can be replaced in a test, and tools such as MSW (Mock Service Worker) intercept requests in front of the network layer. They need npm packages, so they are only mentioned here. The principle is the same: test your code against a fake server, never against production.

A handler tested against a mock API

The example below uses the real node:test runner. It writes a handler file and a test file, runs the tests programmatically, and prints one line per test (a custom reporter keeps timings out of the output). The handler fetches an order for each new webhook event, builds a notification message and skips duplicates. The API is a mock that counts calls. Real BigCommerce payloads and signatures are richer; this keeps only what the tests need.

Node.js Unit-test a webhook handler with a mock API

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.

Three tests pass and the last fails on purpose: the handler formats 4590 cents as $45.90, not $45.9. The third test matters most in practice. If the handler marked the event as seen before the fetch succeeded, the platform's retry of a failed delivery would be ignored forever and the notification would be lost. Writing the failure test is how you find that kind of bug before a shopper does.

Testing Stencil themes

A Stencil theme is Handlebars templates, SCSS and JavaScript. Test it in layers, too:

  • Pure JavaScript in your theme (formatters, quantity logic, filter state) can be unit tested like any module, as long as you keep DOM access at the edges. Cornerstone itself ships Jest configuration for this.
  • Templates and settings are checked with stencil start and by loading pages that exercise every branch: a product with no image, with many variants, out of stock, with a very long name. Most theme bugs are empty-state bugs.
  • The bundle is checked with stencil bundle, which fails on invalid config.json, schema.json or template syntax, and stencil push to a sandbox store to run a real preview. Pushing to the sandbox in CI before every release catches a broken bundle early.
  • Visual and accessibility checks with a browser automation tool (for example Playwright or Cypress, both beyond this course) catch layout and keyboard problems that unit tests cannot see.

You cannot run a theme here, but you can test the logic you extract from it, as in the Handlebars Templates lesson's renderer.

Sandbox flows

Keep a dedicated development store. Automate what you can with a script that creates fixtures (a product with variants, a customer, a test order) using the API, runs the scenario and cleans up. Rules for sandbox tests:

  • Never run them against a live store. Use a separate API account with only the scopes the test needs.
  • Make them repeatable: create data with unique names, delete it at the end, and tolerate leftovers from a failed earlier run.
  • Mind the rate limits and the shared state; run one sandbox suite at a time.
  • Use payment providers' test modes for checkout flows, as covered in Payments Overview.

Webhooks need a public URL to reach your laptop. A tunnelling tool gives you one for development; for automated tests, prefer sending your own signed sample payloads straight to the handler.

Contract tests

Your code depends on the shape of API responses: data is an array, meta.pagination.total_pages exists, an order has status_id. A contract test records those expectations as a small schema and checks real responses (from a sandbox, or saved examples) against it. When the platform adds a field, nothing breaks. When it renames or removes one you rely on, the contract test fails with a message that names the field, long before production does.

The check below is a hand-written mini contract validator. It compares a response to a description of types, lists problems with their paths, and ignores extra fields on purpose. Real projects use JSON Schema libraries for the same job.

Node.js A tiny contract check for API responses

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 good response passes even with an unexpected extra field, which is what lets the platform evolve. The drifted response reports four precise problems, which is far better than a vague "undefined is not a function" three layers down. Note that total_inc_tax is a string in this fake example; always check the real reference for types, and see Money as Integers for converting safely.

What to run when

  • On every commit: unit tests and mock-API integration tests, plus stencil bundle for themes.
  • On every pull request: contract tests against saved examples, and lint.
  • Before a release: the sandbox suite and a manual pass through checkout.
  • On a schedule: the contract tests against the live sandbox, so API drift is noticed even when you did not change anything.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should a webhook handler receive its API client as a parameter?

    Injecting dependencies lets you test the logic without the network and simulate failures on demand.
  2. 2. In the handler example, why must the event be marked as seen only after the order was fetched successfully?

    If a failing event were remembered, the platform's retry would look like a duplicate and be dropped, losing the notification.
  3. 3. What is a contract test for?

    A contract describes the fields and types you rely on; checking real responses against it exposes drift early.
  4. 4. Which tests should run against a dedicated sandbox store rather than on every commit?

    Sandbox flows are slow and share state, so keep them few and run them before releases. Pure functions are tested instantly with unit tests.

Summary

  • Layer your tests: many fast unit tests, some mock-API integration tests, a few sandbox flows.
  • Write handlers as functions that receive their dependencies so they are easy to fake.
  • Give mocks realistic failures and record their calls; assert on what was not called, too.
  • For themes, test extracted JavaScript, empty states, stencil bundle and a sandbox preview.
  • Keep sandbox tests repeatable and separate from live stores and tokens.
  • Contract tests catch API drift by checking only the fields you depend on.

Next: Performance, Security and Launch