DEV Community

Aleksander Sekowski
Aleksander Sekowski

Posted on Fully Autonomous

Conversion payload tests should preserve JSON types through serialization.

A purchase amount can begin as a JavaScript number and leave the application as a JSON string. The log still shows 19.99, so a quick visual check may miss the change.

This happens when payloads pass through templates, CSV imports, form handlers or middleware that represent every value as text. A test on the original object cannot establish what the final HTTP body contains.

The useful boundary is the serialized payload. Build it through the real adapter, inspect the bytes you intend to send and validate the resulting JSON types against the destination contract.

Keep amounts and identifiers distinct

In the GA4 purchase contract, value is numeric while transaction_id is a string. A numeric-looking identifier should not be converted into an amount merely because it contains digits.

The identifier 000012 illustrates the problem. Converting it to a number discards the leading zeros. Converting it back to text later does not recover the original value.

Define the internal type of each field before normalization. A generic convert-all-numeric-strings helper has no basis for deciding which strings are identifiers and which represent quantities.

Test the body after JSON serialization

This complete Node.js program checks two fields in a synthetic GA4 purchase fragment. It is a focused type test, not a complete purchase validator:

import assert from 'node:assert/strict';

function typeIssues(serialized) {
  let payload;
  try { payload = JSON.parse(serialized); }
  catch { return ['invalid JSON']; }
  const params = payload?.events?.[0]?.params;
  if (!params || typeof params !== 'object' || Array.isArray(params)) {
    return ['purchase params missing'];
  }
  const issues = [];
  if (typeof params.value !== 'number' || !Number.isFinite(params.value)) {
    issues.push('value must be a finite number');
  }
  if (typeof params.transaction_id !== 'string' ||
      params.transaction_id.trim().length === 0) {
    issues.push('transaction_id must be a nonempty string');
  }
  return issues;
}

const makePayload = value => ({ events: [{ name: 'purchase', params: {
  value, currency: 'USD', transaction_id: '000012'
} }] });

assert.deepEqual(typeIssues(JSON.stringify(makePayload(19.99))), []);
assert.deepEqual(typeIssues(JSON.stringify(makePayload('19.99'))),
  ['value must be a finite number']);
assert.deepEqual(typeIssues(JSON.stringify(makePayload(NaN))),
  ['value must be a finite number']);
assert.deepEqual(typeIssues(JSON.stringify(makePayload(Infinity))),
  ['value must be a finite number']);
assert.deepEqual(typeIssues('{broken'), ['invalid JSON']);
assert.deepEqual(typeIssues('{}'), ['purchase params missing']);
assert.equal(JSON.parse(JSON.stringify(makePayload(19.99)))
  .events[0].params.transaction_id, '000012');
assert.equal(JSON.parse(JSON.stringify(makePayload(NaN)))
  .events[0].params.value, null);
Enter fullscreen mode Exit fullscreen mode

The final assertion shows why checking before serialization is insufficient. JavaScript's non-finite number becomes JSON null. The body remains valid JSON, but the value has changed meaning.

Missing properties need attention too. Serializing an object property whose value is undefined omits it. A later test should distinguish an absent required value from a valid zero.

Normalize text inputs in a named adapter

If an upstream format supplies text, parse that text once at a documented boundary. Reject empty input and unsupported formats before calling a numeric conversion.

For example, Number("") and Number(" ") produce zero. That behavior is convenient for some calculations and dangerous when an empty purchase amount should be rejected as missing data.

Specify which decimal format the adapter accepts. A string containing a comma might represent a thousands separator or a decimal separator depending on its origin. Removing punctuation indiscriminately can turn an invalid input into a plausible but incorrect amount.

Keep the original input available in a controlled failure record when needed. The normalized number alone cannot explain whether a producer supplied zero, omitted the value or sent an unsupported string.

This policy belongs to the input adapter. The destination validator should then inspect the normalized outgoing value under the endpoint's contract.

Exercise transformations after your first validation step

A payload can pass validation and then change inside a rendering template, HTTP wrapper or tag manager. Put a test transport at the last application-controlled boundary and capture the actual body passed to it.

Compare types in the parsed captured body. Comparing two formatted log lines is weaker because log formatting may hide whether the original JSON token had quotes.

Also include an adapter fixture with a custom serializer or toJSON transformation if your codebase uses one. Serialization behavior is executable code and can alter fields after ordinary object validation.

Run the same fixture through the batch path if events are batched. A separate batch builder may stringify or merge values differently from the single-event path you first tested.

Keep monetary rules separate from JSON type rules

A finite number is not automatically a correct purchase amount. The application still needs a policy for currency, tax, shipping, discounts and the source of the final order total.

Likewise, JSON type validation does not settle decimal arithmetic. If the order system uses integer minor units or a decimal library, test the conversion to the endpoint's amount representation explicitly. Do not apply display rounding in an unrelated template and reuse that result as the authoritative purchase value.

Include a fixture with a zero amount and decide whether the business operation permits it. That decision should be visible rather than emerging from a truthiness check such as value || fallback.

The small test here intentionally leaves those business rules outside its scope. It answers whether the serialized field has the expected type and whether the identifier survived unchanged.

Use a failed wire fixture as the regression

When a production adapter emits a quoted amount, keep a sanitized copy of that exact serialized shape. Add the corrected shape and assert the expected finding for each.

Record the adapter revision and destination contract used by the test. A future developer can then reproduce the type change without needing access to the original customer event.

I maintain Pixellint. Its GA4 payload pack can inspect a broader purchase payload. Keep the captured-body test in your integration as well, since it protects the point where your application converts an internal object into the bytes actually sent.

Sources

Technical sources checked October 25, 2026. Drafted with AI; examples are synthetic unless explicitly stated otherwise.

Top comments (0)