Skip to content
ImagineWorld

Testing & Debugging

node_idnode-book_rust-wasm-fusion_chapter-06-testing-and-debugging
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num6
chapter_titleTesting & Debugging
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Building high-quality Rust→Wasm modules means more than just writing code and bundling it—it demands thorough testing and effective debugging.


Robust unit tests give you confidence that your Rust-compiled Wasm behaves exactly as expected—across updates, refactors, and browser variations. wasm-pack test leverages Rust’s native test harness but runs your code inside real browser engines (Chrome or Firefox) or Node.js, catching issues that plain cargo test can’t. Let’s dive into the workflow, see a working example, and explore how to interpret results.


  • Real Engine Validation: Ensures your Wasm module runs correctly in actual JavaScript environments, not just inside the Rust runtime.
  • Catch Interop Bugs: Browser tests surface issues in your glue code—string marshaling, memory errors, or missing imports—that cargo test alone wouldn’t reveal.
  • Cross-Browser Confidence: Running tests in both Chrome and Firefox flags engine-specific quirks early.

flowchart LR A[Write Rust Unit Tests] —> B[wasm-pack build wasm32-unknown-unknown] B —> C[wasm-bindgen generate JS glue] C —> D[Spawn Browser (headless)] D —> E[Execute tests in browser context] E —> F[Report Pass/Fail in Terminal]


Place test functions alongside your code in src/lib.rs, or in a separate tests/ module:

src/lib.rs
use wasm_bindgen::prelude::*;
/// Adds two 32-bit integers.
#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn add_positive() {
assert_eq!(add(1, 2), 3);
}
#[test]
fn add_negative() {
assert_eq!(add(-5, 3), -2);
}
#[test]
#[should_panic]
fn overflow_panics() {
// Intentional overflow
let _ = add(i32::MAX, 1);
}
}
  • #[cfg(test)] blocks ensure tests compile only in test mode.
  • Use #[should_panic] to verify error cases.

From your crate’s root directory, execute:

Terminal window
wasm-pack test --headless --chrome
  • --headless: Runs without opening a UI.
  • --chrome (or --firefox): Specifies the browser engine.
  • Default: If no browser flag is given, runs in both.
Compiling hello_browser v0.1.0
Finished test [unoptimized + debuginfo] target(s) in 2.34s
Running unittests in wasm...
running 3 tests
test tests::add_positive ... ok
test tests::add_negative ... ok
test tests::overflow_panics ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured

Insight: On CI servers without Chrome installed, fallback to Node.js:

Section titled “Insight: On CI servers without Chrome installed, fallback to Node.js:”
wasm-pack test --headless --node

When a test fails, you’ll see a panic message and a stack trace that maps back to your Rust source:

---- tests::add_negative stdout ----
thread 'tests::add_negative' panicked at 'assertion failed: `(left == right)`
left: `-1`,
right: `-2`, src/lib.rs:15:9
  • File and line number point directly to the failing assert_eq!.
  • Use this information to correct logic or interop issues in your Rust code.

Scenario: In a function that returned a greeting string, tests passed under cargo test but failed in Chrome with a decoding error.

Investigation: The JS glue was using the wrong length when reading back the string.

Fix: I noticed the Rust function was returning a trimmed buffer; adding a

.clone() on the String before returning ensured the correct length exported.

Takeaway: Browser-backed tests are invaluable for catching glue-specific bugs you can’t see in plain Rust tests.


  • Run tests frequently: Integrate wasm-pack test into your pre-commit hooks for immediate feedback.
  • Use --firefox to catch WebKit vs. Chromium differences early.
  • Combine with coverage tools: Although still maturing for Wasm, tools like kcov can help measure test coverage.
  • Debug tests: Omit --headless to watch tests run in a real browser window, set breakpoints in DevTools, and step through your Rust.

  • Write tests in Rust as usual (#[test], assert_eq!, etc.).
  • Execute tests in real browser engines via wasm-pack test --headless --chrome|--firefox or --node.
  • Interpret failures with clear stack traces back to your .rs files.
  • Catch interop bugs and marshaling issues that cargo test alone would miss.

While wasm-pack test gives you quick feedback in real browser engines or Node, larger projects often require integrating your Wasm tests into established JavaScript test suites—Jest, Mocha, or even Karma.

  1. Unified CI pipelines: One command (npm test) runs all tests—JS, Rust-Wasm, integration specs.
  2. Rich ecosystems: Leverage snapshots, coverage reports, and reporters you already use.
  3. Mocking & fixtures: Use familiar patterns for HTTP mocks, DOM fixtures, and timers.

A[Write tests: Rust & JS] —> B[Test Runner] B —> C(Environment) C — Node —> D[Jest/Mocha] C — Browser —> E[Karma/Playwright] D & E —> F[Results & Coverage]

Jest is the de facto standard for JS/TS testing. With its built-in Wasm support and async capabilities, it handles Wasm modules gracefully.

Terminal window
npm install --save-dev jest ts-jest jest-raw-loader @types/jest
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
moduleFileExtensions: ['js', 'ts', 'wasm'],
transform: {
'^.+\\.ts$': 'ts-jest',
'^.+\\.wasm$': 'jest-raw-loader'
},
globals: {
'ts-jest': { useESM: true }
}
};
import init, { greet } from '../pkg/your_crate.js';
<!-- page: 071 -->
beforeAll(async () => {
await init();
});
test('greet returns personalized message', () => {
expect(greet('Jest')).toBe('Hello, Jest! Welcome to Rust-Wasm.');
});
4. Run Tests
npx jest
Personal Insight:
I once forgot to await init(), and tests failed randomly. Ensuring beforeEach(async...) stabilized my suite across CI runs.
C. Node.js Test Runner: Mocha + Chai
For teams using Mocha:
1. Install
npm install --save-dev mocha chai ts-node chai-as-promised
2. Configure in package.json
json
"scripts": {
"test": "mocha -r ts-node/register \"test/**/*.spec.ts\""
}
  1. Write a Test (test/add.spec.ts)
import { expect } from 'chai';
import init, { add } from '../pkg/your_crate.js';
describe('add()', () => {
beforeEach(async () => { await init(); });
it('adds two numbers', () => {
expect(add(4, 5)).to.equal(9);
});
});
<!-- page: 072 -->
4. Run
5. npm test
**Case Study:**
In a legacy codebase with Mocha, integrating Wasm via ts-node let us write hybrid tests—verifying both pure JS utilities and Rust-backed functions in one suite.
---
**D. Browser Test Runner: Karma**
When you need a real browser matrix:
1. **Install**
bash
npm install --save-dev karma karma-chrome-launcher karma-mocha karma-webpack
  1. Configure (karma.conf.js)
module.exports = function(config) {
config.set({
frameworks: ['mocha'],
files: ['test/**/*.browser.spec.js'],
preprocessors: { 'test/**/*.browser.spec.js': ['webpack'] },
webpack: { /* reuse your webpack.config.js, ensure asyncWebAssembly */ },
browsers: ['ChromeHeadless'],
singleRun: true
});
};
  1. Write a Browser Test (test/greet.browser.spec.js)
import init, { greet } from '../pkg/your_crate.js';
describe('greet (browser)', () => {
before(async () => { await init(); });
it('greets in browser', () => {
const msg = greet('Karma');
chai.expect(msg).to.contain('Karma');
});
});
  1. Run

  2. npx karma start

Expert Commentary:

Browser-based runners catch issues like missing CSP headers or incorrect MIME types—problems Node tests would never flag.


  • Jest and Mocha excel for Node.js–based testing: simple setup, fast iterations, and tight CI integration.
  • Karma (or alternatives like Playwright Test) let you verify behavior in actual browsers and multiple versions.
  • Always await init() before calling your Wasm exports—this common mistake causes flakiness.
  • Unified suites that mix JS and Rust-Wasm tests streamline your CI and reduce context switching for developers.

6.3: Source-Map-Backed Debugging in DevTools

Section titled “6.3: Source-Map-Backed Debugging in DevTools”

When you step through WebAssembly without source maps, you see raw bytecode instructions—an opaque, unwieldy world. Source maps bridge that gap, mapping Wasm back to your original Rust code so you can set breakpoints, inspect variables, and follow the execution flow just like in a native debugger. Let’s explore how to generate these maps, wire them into your bundler, and leverage Chrome DevTools for seamless Rust-level debugging.


  • Clarity: See your .rs files, not Wasm offsets.
  • Productivity: Set breakpoints on the exact line where your logic lives.
  • Insight: Inspect local variables and call stacks in Rust terms.

flowchart LR A[Write Rust Code] —> B[Compile with debug info] B —> C[wasm-bindgen + —source-map] C —> D[Bundler includes .wasm.map] D —> E[DevTools fetch .wasm and .map] E —> F[Display .rs in Sources panel] F —> G[Set breakpoints & inspect]


B. Generating Wasm Source Maps

  1. Enable debug info in Cargo In your Cargo.toml: 2. [profile.dev] 3. debug = true

  2. Run wasm-pack with — flags 5. wasm-pack build —dev — —profiling —source-map

    • —profiling: Retains frame information.
    • —source-map: Emits a .wasm.map alongside your .wasm.
  3. Verify artifacts In pkg/, you should now see: 7. your_crate_bg.wasm 8. your_crate_bg.wasm.map 9. your_crate.js 10. your_crate.d.ts

Personal Insight: I once spent hours tracing a logic bug only to realize my build stripped debug info. Adding —source-map transformed my workflow—breakpoints snapped to Rust lines instantly.


C. Configuring Bundlers to Serve Source Maps Vite

In vite.config.js, enable sourcemaps:

import { defineConfig } from ‘vite’;

export default defineConfig({ build: { sourcemap: true } });

Vite will copy .wasm.map into the served directory so DevTools can locate it.

Webpack

In webpack.config.js:

module.exports = {
mode: 'development',
devtool: 'source-map',
experiments: { asyncWebAssembly: true },
module: {
rules: [
{
test: /\.wasm$/,
type: 'webassembly/async'
}
]
}
}

Webpack’s devtool: 'source-map' ensures it references your .wasm.map correctly.

Rollup

In rollup.config.js:

export default {
output: {
sourcemap: true,
format: 'esm',
dir: 'public'
},
plugins: [ /* your plugins */ ]
};

Rollup will include sourceMappingURL comments pointing to the .wasm.map.

D. Debugging in Chrome DevTools

  1. Open DevTools (F12) and go to the Sources panel.
  1. Locate your Rust files

    • Under the webpack://, vite://, or rollup:// origin, expand to find your crate’s .rs files.
  2. Set breakpoints

    • Click the line number in the .rs file to set a breakpoint.
  3. Trigger execution

    • Perform the user action in your page that invokes the Wasm function.
    • DevTools will pause on your Rust line.
  4. Inspect variables and call stack

    • Hover over variables to see their Rust values.
    • Step over (F10), into (F11), or out (Shift+F11) just like in a native Rust debugger.

Sources

vite://
├── src
│ └── your_crate_rs
│ ├── lib.rs
│ └── utils.rs

Expert Tip:

If you don’t see your .rs files, check that the .wasm.map is being served (Network tab) and that the sourceMappingURL at the end of the .wasm binary points correctly to it.


In a data-processing module, I encountered an unexpected panic in production builds. With source maps enabled:

  1. I opened DevTools on the staging URL.
  2. Set a breakpoint on the Rust function where I suspected the error.
  3. Re-ran the data processing UI, and DevTools paused right at the panic site, showing the offending index out of bounds.
  4. I immediately spotted a missing range check and patched it—an edit that would have been far harder without stepping through the Rust source.
  • Compile with --source-map and debug = true to generate .wasm.map.
  • Configure your bundler to preserve and serve source maps.
  • Use DevTools Sources panel to navigate and debug Rust code directly.
  • Verify mapping by checking network requests for your .wasm.map.
  • Stepping through Rust in the browser feels like native debugging—use it to crush subtle logic bugs.

With source-map-backed debugging, your Rust-Wasm development experience reaches parity with JavaScript.