Testing WebAssembly/JavaScript Interop: Type Marshaling, Memory, and API Design
The boundary between WebAssembly and JavaScript is where most WASM bugs live. WASM modules are fast and correct in isolation, but the moment data crosses the JS/WASM boundary, you encounter type coercions, memory management responsibilities, encoding issues, and error propagation challenges that none of your source-language tests will catch. This guide covers how to test the JS/WASM interop layer systematically.
Understanding the JS/WASM Boundary
Every interaction between JavaScript and WebAssembly must cross the boundary. WASM can only directly pass and receive:
i32,i64,f32,f64(numeric primitives)externref(reference to a JavaScript object — newer WASM)- Linear memory pointers (integers referring to addresses in
WebAssembly.Memory)
Everything else — strings, arrays, objects, callbacks — requires manual serialization through WebAssembly.Memory. This is called "type marshaling," and it's a source of bugs, performance issues, and subtle encoding errors.
Higher-level tools like wasm-bindgen (Rust) or emscripten_bind (C++) generate marshaling code automatically, but you still need to test that the generated bindings work correctly.
Testing Primitive Type Passing
Start with the simplest case — ensure numeric types round-trip correctly:
// tests/interop/primitives.test.js
import init, {
add_i32, multiply_f64, max_i32, min_f32, round_trip_i64
} from '../dist/module.js';
describe('Primitive Type Interop', () => {
beforeAll(async () => {
await init();
});
describe('Integer types', () => {
it('handles i32 positive values', () => {
expect(add_i32(10, 20)).toBe(30);
});
it('handles i32 negative values', () => {
expect(add_i32(-10, -20)).toBe(-30);
});
it('wraps on i32 overflow', () => {
const MAX_I32 = 2147483647;
expect(add_i32(MAX_I32, 1)).toBe(-2147483648);
});
it('handles i32 minimum value', () => {
const MIN_I32 = -2147483648;
expect(add_i32(MIN_I32, -1)).toBe(2147483647);
});
it('truncates JavaScript floats to i32', () => {
// JavaScript numbers are f64; passing 1.9 as i32 truncates to 1
expect(add_i32(1.9, 2.1)).toBe(3); // truncated to 1 + 2
});
});
describe('Float types', () => {
it('handles f64 precision', () => {
const result = multiply_f64(0.1, 0.2);
expect(result).toBeCloseTo(0.02, 15);
});
it('handles Infinity', () => {
expect(multiply_f64(Infinity, 2)).toBe(Infinity);
});
it('propagates NaN', () => {
expect(isNaN(multiply_f64(NaN, 1))).toBe(true);
});
it('handles negative zero', () => {
const result = multiply_f64(-0.0, 1.0);
expect(Object.is(result, -0)).toBe(true);
});
});
});Testing String Marshaling
Strings are the most common source of interop bugs. UTF-8 encoding, null termination, and memory ownership all need explicit testing:
describe('String Interop', () => {
describe('ASCII strings', () => {
it('passes simple ASCII string', () => {
const result = wasm.string_length('hello');
expect(result).toBe(5);
});
it('handles empty string', () => {
expect(wasm.string_length('')).toBe(0);
});
it('returns string from WASM', () => {
const result = wasm.get_greeting('World');
expect(result).toBe('Hello, World!');
});
});
describe('Unicode strings', () => {
it('handles multi-byte UTF-8 characters', () => {
// '€' is 3 bytes in UTF-8, but 1 code point
const result = wasm.string_length('€');
// Depends on whether your WASM counts bytes or code points
// Document and test the contract explicitly
expect(result).toBe(1); // or 3, document which it should be
});
it('handles emoji (4-byte UTF-8)', () => {
const emoji = '🚀';
const result = wasm.process_string(emoji);
expect(result).not.toBeNull();
});
it('handles Chinese characters', () => {
const chinese = '你好世界';
const result = wasm.string_length(chinese);
expect(result).toBe(4); // 4 code points
});
it('handles strings with null bytes', () => {
// C-style strings terminate at null bytes
// Your binding may or may not handle this correctly
const withNull = 'hello\0world';
// Document whether null bytes are supported
// If not, test that the function handles this gracefully
const result = wasm.process_string(withNull);
// Either the function processes the full string or truncates at null
// Pick one and test it explicitly
expect(result).toBeDefined();
});
});
describe('Large strings', () => {
it('handles very long strings', () => {
const longString = 'a'.repeat(1000000);
expect(() => wasm.string_length(longString)).not.toThrow();
});
});
});Testing Array and Buffer Marshaling
Arrays require the most careful testing because of memory management:
describe('Array/Buffer Interop', () => {
describe('TypedArray passing', () => {
it('processes Float32Array correctly', () => {
const input = new Float32Array([1.0, 2.0, 3.0, 4.0]);
const result = wasm.sum_f32_array(input);
expect(result).toBeCloseTo(10.0);
});
it('handles empty array', () => {
const empty = new Float32Array(0);
expect(wasm.sum_f32_array(empty)).toBe(0);
});
it('handles single element', () => {
const single = new Float32Array([42.5]);
expect(wasm.sum_f32_array(single)).toBeCloseTo(42.5);
});
it('does not modify input array', () => {
const input = new Float32Array([1.0, 2.0, 3.0]);
const inputCopy = new Float32Array(input);
wasm.normalize_in_place(input);
// Verify the original wasn't unexpectedly modified
// (or verify it was, if that's the contract)
});
});
describe('Return array ownership', () => {
it('returned arrays do not alias WASM memory after GC', () => {
let result = wasm.create_array(100);
const firstValue = result[0];
// Force GC (in Node.js)
if (global.gc) global.gc();
// If the array was properly copied out of WASM memory,
// it should still be valid
expect(result[0]).toBe(firstValue);
});
});
describe('Large buffers', () => {
it('handles 10MB buffer', () => {
const size = 10 * 1024 * 1024 / 4; // 10MB of f32
const data = new Float32Array(size).fill(1.0);
expect(() => wasm.process_large_buffer(data)).not.toThrow();
});
});
});Testing Callbacks: JavaScript → WASM → JavaScript
Callbacks are especially tricky because they require passing function references across the boundary:
describe('Callback Interop', () => {
it('calls JavaScript callback from WASM', () => {
const callbackLog = [];
const callback = (value) => {
callbackLog.push(value);
};
wasm.iterate_and_call(new Float64Array([1, 2, 3, 4, 5]), callback);
expect(callbackLog).toEqual([1, 2, 3, 4, 5]);
});
it('handles callback that throws', () => {
const throwingCallback = () => {
throw new Error('Callback error');
};
// Test that an error in a callback propagates correctly
expect(() => {
wasm.iterate_and_call(new Float64Array([1, 2, 3]), throwingCallback);
}).toThrow('Callback error');
});
it('handles async callbacks', async () => {
const results = [];
const asyncCallback = async (value) => {
await new Promise(resolve => setTimeout(resolve, 1));
results.push(value * 2);
};
await wasm.async_iterate(new Float64Array([1, 2, 3]), asyncCallback);
expect(results).toEqual([2, 4, 6]);
});
it('does not hold callback reference after completion', () => {
let callbackRef = jest.fn();
const weakRef = new WeakRef(callbackRef);
wasm.single_callback_call(callbackRef);
callbackRef = null;
if (global.gc) global.gc();
// Callback should be GC-able after use
// (If WASM holds it indefinitely, this will fail after GC)
expect(weakRef.deref()).toBeUndefined();
});
});Testing Error Propagation
WASM doesn't have native exception handling (beyond wasm-exceptions proposal). Test how errors cross the boundary:
describe('Error Propagation', () => {
it('propagates WASM panic to JavaScript', () => {
// Rust panic, C abort, etc.
expect(() => wasm.cause_panic()).toThrow();
});
it('returns error code for recoverable errors', () => {
const result = wasm.parse_number('not-a-number');
// Depending on your API design:
// Option 1: Returns a sentinel value
expect(result).toBe(-1); // error sentinel
// Option 2: Returns a Result object
// expect(result.ok).toBe(false);
// expect(result.error).toContain('parse error');
});
it('handles division by zero', () => {
// In WASM, integer division by zero is a trap (throws)
// Float division by zero returns Infinity
expect(wasm.divide_f64(1.0, 0.0)).toBe(Infinity);
expect(() => wasm.divide_i32(10, 0)).toThrow();
});
it('provides meaningful error messages', () => {
try {
wasm.process_invalid_input(null);
} catch (e) {
expect(e.message).toMatch(/invalid|null|error/i);
}
});
});Testing Memory Growth and Limits
WASM memory can grow dynamically. Test that your module handles growth correctly:
describe('Memory Management Interop', () => {
it('handles memory growth without invalidating views', () => {
const wasm = getWasmInstance();
// Get initial memory view
const initialBuffer = wasm.exports.memory.buffer;
// Allocate enough to trigger memory growth
const largePtr = wasm.exports.malloc(50 * 1024 * 1024); // 50MB
const newBuffer = wasm.exports.memory.buffer;
if (initialBuffer !== newBuffer) {
// Memory grew — any views into the old buffer are now detached
// Test that your binding handles this correctly
// Create new view into new buffer
const newView = new Uint8Array(newBuffer, 0, 100);
expect(() => newView[0]).not.toThrow();
// Old view should be detached
const oldView = new Uint8Array(initialBuffer, 0, 100);
expect(oldView.byteLength).toBe(0); // detached
}
wasm.exports.free(largePtr);
});
it('detects use-after-free through canary values', () => {
const ptr = wasm.exports.malloc(100);
const view = new Uint8Array(wasm.exports.memory.buffer, ptr, 100);
view[0] = 0xAB; // Write canary
wasm.exports.free(ptr);
// The value at the freed pointer may have changed
// Test that your code doesn't access freed memory
// (In a test environment with debug allocator, this may also throw)
});
});Integration Testing with Real Workloads
After unit testing individual interop functions, test complete workflows:
describe('End-to-End Interop', () => {
it('processes complete image pipeline', async () => {
// Load a real image
const imageData = await loadTestImage('./fixtures/test-image.png');
const { pixels, width, height } = imageData;
// Run full WASM pipeline
const result = await wasm.process_image_pipeline({
pixels: new Uint8ClampedArray(pixels),
width,
height,
operations: ['grayscale', 'blur', 'sharpen']
});
// Verify output structure
expect(result.pixels).toBeInstanceOf(Uint8ClampedArray);
expect(result.pixels.length).toBe(width * height * 4);
expect(result.width).toBe(width);
expect(result.height).toBe(height);
// Verify specific pixel values match expected output
const expectedPixels = await loadExpectedOutput('./fixtures/expected-output.png');
let maxDiff = 0;
for (let i = 0; i < result.pixels.length; i++) {
maxDiff = Math.max(maxDiff, Math.abs(result.pixels[i] - expectedPixels[i]));
}
// Allow small rounding differences
expect(maxDiff).toBeLessThan(2);
});
});Testing with HelpMeTest
For production monitoring of your WASM/JS interop:
*** Test Cases ***
WASM Module Integration Test
[Documentation] Verify WASM/JS interop works in production browser
Go To https://your-app.com
Wait For Service Worker activated
${result}= Evaluate JavaScript
... async () => {
... const mod = await import('/wasm-module.js');
... await mod.default();
... const result = mod.process_string('test');
... return typeof result === 'string';
... }
Should Be True ${result}Common Interop Testing Pitfalls
1. Not testing the generated bindings code. wasm-bindgen generates JS glue code that can have bugs. Test the generated bindings, not just your Rust/C code.
2. Assuming UTF-8 byte length equals string length. '€'.length === 1 in JavaScript, but it's 3 bytes in UTF-8. Test with non-ASCII strings.
3. Not testing memory buffer detachment after growth. If your WASM module grows its memory, all existing TypedArray views into the old buffer become detached and unusable.
4. Not testing the empty/null/undefined edge cases. What does your WASM function do when passed null? undefined? An empty array? Test these explicitly.
5. Testing in Node.js only. Browser WASM implementations have subtle differences from Node.js. Run your integration tests in a real browser.
Conclusion
JS/WASM interop testing is distinct from testing your WASM logic. You're testing the contract between two different type systems, memory models, and error handling approaches. Write tests specifically for type coercions, string encoding, memory ownership, callback behavior, and error propagation. These tests will catch bugs that no amount of source-language unit testing can find.