Testing & Debugging
local graph
Chapter 6 — Testing & Debugging
Section titled “Chapter 6 — Testing & Debugging”Chapter 6 – Testing & Debugging
Section titled “Chapter 6 – Testing & Debugging”Building high-quality Rust→Wasm modules means more than just writing code and bundling it—it demands thorough testing and effective debugging.
6.1: Unit Testing with wasm-pack test
Section titled “6.1: Unit Testing with wasm-pack test”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.
A. Why Browser-Backed Tests Matter
Section titled “A. Why Browser-Backed Tests Matter”- 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 testalone 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]
B. Writing Tests in Your Crate
Section titled “B. Writing Tests in Your Crate”Place test functions alongside your code in src/lib.rs, or in a separate tests/ module:
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.
C. Running Tests with wasm-pack
Section titled “C. Running Tests with wasm-pack”From your crate’s root directory, execute:
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.
Sample Output:
Section titled “Sample Output:”Compiling hello_browser v0.1.0Finished test [unoptimized + debuginfo] target(s) in 2.34sRunning unittests in wasm...running 3 teststest tests::add_positive ... oktest tests::add_negative ... oktest tests::overflow_panics ... oktest result: ok. 3 passed; 0 failed; 0 ignored; 0 measuredInsight: 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 --nodeD. Interpreting Failures
Section titled “D. Interpreting Failures”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.
E. Case Study: Catching a Marshaling Bug
Section titled “E. Case Study: Catching a Marshaling Bug”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.
F. Personal Tips
Section titled “F. Personal Tips”- Run tests frequently: Integrate
wasm-pack testinto your pre-commit hooks for immediate feedback. - Use
--firefoxto catch WebKit vs. Chromium differences early. - Combine with coverage tools: Although still maturing for Wasm, tools like
kcovcan help measure test coverage. - Debug tests: Omit
--headlessto 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|--firefoxor--node. - Interpret failures with clear stack traces back to your
.rsfiles. - Catch interop bugs and marshaling issues that
cargo testalone would miss.
6.2: Browser & Node.js Test Runners
Section titled “6.2: Browser & Node.js Test Runners”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.
A. Why Integrate with JS Test Runners?
Section titled “A. Why Integrate with JS Test Runners?”- Unified CI pipelines: One command (
npm test) runs all tests—JS, Rust-Wasm, integration specs. - Rich ecosystems: Leverage snapshots, coverage reports, and reporters you already use.
- Mocking & fixtures: Use familiar patterns for HTTP mocks, DOM fixtures, and timers.
flowchart TD
Section titled “flowchart TD”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]
B. Node.js Test Runner: Jest
Section titled “B. Node.js Test Runner: Jest”Jest is the de facto standard for JS/TS testing. With its built-in Wasm support and async capabilities, it handles Wasm modules gracefully.
1. Install Dependencies
Section titled “1. Install Dependencies”npm install --save-dev jest ts-jest jest-raw-loader @types/jest2. Configure Jest (jest.config.js)
Section titled “2. Configure Jest (jest.config.js)”module.exports = { preset: 'ts-jest', testEnvironment: 'node', moduleFileExtensions: ['js', 'ts', 'wasm'], transform: { '^.+\\.ts$': 'ts-jest', '^.+\\.wasm$': 'jest-raw-loader' }, globals: { 'ts-jest': { useESM: true } }};3. Write a Test (__tests__/greet.test.ts)
Section titled “3. Write a Test (__tests__/greet.test.ts)”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\""}- 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**
bashnpm install --save-dev karma karma-chrome-launcher karma-mocha karma-webpack- 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 });};- 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'); });});-
Run
-
npx karma start
Expert Commentary:
Browser-based runners catch issues like missing CSP headers or incorrect MIME types—problems Node tests would never flag.
Key Takeaways
Section titled “Key Takeaways”- 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.
A. Why Source Maps Matter
Section titled “A. Why Source Maps Matter”- Clarity: See your
.rsfiles, 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
-
Enable debug info in Cargo In your Cargo.toml: 2. [profile.dev] 3. debug = true
-
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.
-
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
- Open DevTools (F12) and go to the Sources panel.
-
Locate your Rust files
- Under the webpack://, vite://, or rollup:// origin, expand to find your crate’s .rs files.
-
Set breakpoints
- Click the line number in the .rs file to set a breakpoint.
-
Trigger execution
- Perform the user action in your page that invokes the Wasm function.
- DevTools will pause on your Rust line.
-
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.rsExpert 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.
E. Case Study: Stepping Through a Panic
Section titled “E. Case Study: Stepping Through a Panic”In a data-processing module, I encountered an unexpected panic in production builds. With source maps enabled:
- I opened DevTools on the staging URL.
- Set a breakpoint on the Rust function where I suspected the error.
- Re-ran the data processing UI, and DevTools paused right at the panic site, showing the offending index out of bounds.
- I immediately spotted a missing range check and patched it—an edit that would have been far harder without stepping through the Rust source.
Key Takeaways
Section titled “Key Takeaways”- Compile with
--source-mapanddebug = trueto 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.