Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 28 ยท Quality

Testing, Debugging and Logging

Test Salesforce B2C Commerce code: unit tests with mocha and proxyquire, integration tests, Jest for PWA Kit, custom log categories and the script debugger.

Commerce code is full of money, stock and customer data, so a bug is rarely cosmetic. Yet B2C Commerce has an awkward testing problem: your scripts call the platform's own API (dw/system/Logger, dw/catalog/ProductMgr, dw/web/Resource), and that API only exists inside the platform. You cannot require('dw/catalog/ProductMgr') in plain Node. The standard solution is to replace those modules with mocks while testing, so your logic runs on a laptop in milliseconds. When you do need the real platform, you use integration tests, logs and the script debugger on a sandbox.

This lesson shows the testing pyramid for B2C Commerce, how the mock-loading trick works, how to log well, and how to debug a request. Real tool commands and platform calls are read-only here, since they need your project or an instance. The runnable TryIt blocks are stand-ins: they run in plain Node and reproduce the mechanics (a module loader with stubs, a mini test runner, a logger with levels) without the real libraries.

The testing pyramid for a cartridge

flowchart TD
    A["Unit tests<br/>(mocha, chai, sinon, proxyquire)<br/>fast, many"] --> B["Integration tests<br/>(HTTP against a sandbox)<br/>slower, fewer"]
    B --> C["UI or end-to-end tests<br/>(browser automation)<br/>slowest, few"]

Put most of your effort at the bottom: it is the cheapest place to find a bug.

  • Unit tests cover models, decorators, helpers and hook scripts. They run offline.
  • Integration tests call a deployed sandbox over HTTP and check real responses (add to basket, check totals). They need a code version uploaded and test data present.
  • Browser tests drive the real storefront, and are best kept to a handful of critical flows such as "guest checks out".

The SFRA reference project is set up with mocha (test runner), chai (assertions), sinon (spies and stubs) and proxyquire (substituting required modules). The scripts in package.json typically run unit tests through the project's build tooling; check the scripts of your own project for the exact command.

Unit testing with proxyquire

A model such as models/product.js begins with require('dw/web/Resource'). Outside the platform that line would fail. proxyquire loads your file but hands it your stub for each path you list:

JavaScript
'use strict';

var assert = require('chai').assert;
var sinon = require('sinon');
var proxyquire = require('proxyquire').noCallThru().noPreserveCache();

describe('product model', function () {
    var warn = sinon.spy();
    var ProductModel = proxyquire('../../../cartridges/app_custom/cartridge/models/product', {
        'dw/web/Resource': { msg: function (key) { return key; } },
        'dw/system/Logger': { warn: warn }
    });

    it('reports a product without stock as unavailable', function () {
        var model = new ProductModel({
            ID: 'sku-1',
            name: 'Notebook',
            availabilityModel: { inStock: false },
            custom: {}
        });
        assert.isFalse(model.available);
        assert.equal(model.availabilityMessage, 'label.outofstock');
    });
});

Two options matter. noCallThru() means a path you did not stub is not loaded from disk, so a forgotten mock fails loudly instead of quietly reaching for the real thing. noPreserveCache() reloads the module for each proxyquire call, so state does not leak between tests. In the SFRA reference project, a mock library with ready-made fakes of common dw classes is kept in the test folder, so you rarely start from zero.

What to mock, and what not:

  • Mock platform edges: dw/* modules, the server module, other cartridges' scripts you do not own.
  • Do not mock your own pure logic (price math, date arithmetic). Test it directly; that is the point.
  • Keep logic out of controllers. A route that only wires req, res and a helper is easy to leave untested; the helper holds the rules and is easy to test (see Models, Decorators and Helpers).

The first stand-in builds the same mechanism in a few lines, using Node's own assert.

Node.js Stand-in: stub loader and mini test runner (plain Node)

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 is the useful habit: when code asks for something you did not mock, the test should fail with a clear message instead of silently succeeding.

Controllers and hooks

Testing a route end to end offline is possible but heavy, because you must fake server, req and res. A good compromise is to extract the logic into a helper, unit test the helper, and cover the route itself with one integration test. Hook scripts (see Hooks and Extension Mechanisms) are easy to unit test: each exported function takes plain arguments and returns a value, so you can call it directly with a stubbed basket.

Integration tests

Integration tests send real HTTP requests to a sandbox: create a basket, add a product, check the totals. They prove your cartridge, the data and the configuration work together, and they catch problems no mock can (a missing site preference, a wrong cartridge path). They are slower, depend on test data, and can fail for reasons unrelated to your change, so keep them few and focused on money paths. Run them against a sandbox you own, never against production.

Testing a PWA Kit storefront

A headless storefront (see Headless Storefronts with PWA Kit) is an ordinary React app, so it is tested like one: Jest as the runner and React Testing Library to render components. The generated project includes helpers for rendering a component with the providers it needs, and tests usually mock the network (for example with a request-mocking library) rather than calling the real API. Check the test setup that your generated project ships, because it changes between template versions.

Logging

Logs are your window into a running instance. In scripts you use dw/system/Logger:

JavaScript
'use strict';

var Logger = require('dw/system/Logger');

var log = Logger.getLogger('checkout', 'delivery');

log.debug('Estimating delivery for {0}', productId);
log.info('Order {0} placed', order.orderNo);
log.warn('Product {0} has no leadTimeDays', productId);
log.error('Payment service failed: {0}', e.message);

getLogger(prefix, category) takes an optional file prefix and a category. The category lets operators raise or lower the level for just that area in Business Manager's custom log settings, so you can switch on debug for delivery without flooding everything else. Messages use placeholders for arguments. The levels, from quiet to noisy, are error, warn, info and debug; on a production instance the noisy ones are normally off, so a debug line costs little but also shows nothing unless enabled.

Log files are downloadable from the instance (over WebDAV) and viewable in Business Manager's log tooling. Remember:

  • Never log secrets or personal data: card numbers, passwords, tokens, full addresses. Logs are readable by many people and kept for a while (see Security, Sessions and Compliance).
  • Log files are size-limited and old entries rotate away, so do not log inside tight loops.
  • Include an identifier (order number, product ID) so a line can be found and linked to a request.
  • Log the decision, not the whole object: Logger formats with toString, and big objects print as useless text.

The second stand-in models categories, levels and placeholders, so you can see why a debug call is silent until a category is raised.

Node.js Stand-in: a logger with categories and levels

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.

Debugging a request

When logs are not enough you can step through code. The usual route is a code editor extension for B2C Commerce (the community Prophet extension for VS Code is widely used) that connects to the script debugger of a sandbox: you set breakpoints in a cartridge, trigger the request in the storefront and inspect variables. It needs the sandbox credentials from your dw.json (see Setting Up Your Development Environment) and the debugger enabled for the instance. The Storefront Toolkit also offers a request log view on non-production instances, which shows the log messages and details of the request you just made. Debug on a sandbox, not on a production instance.

Common failure modes and where to look first:

Symptom First place to check
Page shows an error with a reference ID The error log around the timestamp
New code has no effect Active code version, cartridge path, cache
"Cannot find module" The require path and which cartridge supplies the file
Works for you, not for others Personalization in a cached page, customer group, locale
Slow request Profiler and request logs (Caching and Performance)

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can't a model that requires dw/web/Resource be tested directly in plain Node?

    The Script API is provided by the platform at runtime. Unit tests replace those modules with stubs, which is what proxyquire does.
  2. 2. What does noCallThru() do in proxyquire?

    Without call-through, an unstubbed dependency is not silently loaded, which exposes forgotten mocks and accidental dependence on real platform code.
  3. 3. Why give a logger a category?

    Levels are configured per category in the custom log settings, so debug output can be switched on just for the area you are investigating.
  4. 4. Which belongs in a log line?

    Identifiers and decisions help debugging. Secrets and personal data must never be logged, because logs are widely readable and retained.

Summary

  • Keep most tests at the unit level, with a few integration tests and even fewer browser tests.
  • Unit tests replace dw/* modules with stubs (proxyquire with noCallThru), so logic runs offline.
  • Move rules out of controllers into helpers and models so they can be tested directly.
  • Headless storefronts are tested like React apps with Jest and mocked network calls.
  • Log with Logger.getLogger(prefix, category), use placeholders, log identifiers and decisions, and never log secrets or personal data.
  • Use the script debugger and the Storefront Toolkit on a sandbox, not on production.
  • The TryIt blocks are stand-ins written in plain Node; the real libraries and platform classes need your project or an instance.

Next: Security, Sessions and Compliance