wasm_bindgen_test/rt/
worker.rs

1//! Support for printing status information of a test suite in a browser.
2//!
3//! Currently this is quite simple, rendering the same as the console tests in
4//! node.js. Output here is rendered in a `pre`, however.
5
6use alloc::format;
7use alloc::string::String;
8use js_sys::Error;
9use wasm_bindgen::prelude::*;
10
11use super::TestResult;
12
13/// Implementation of `Formatter` for browsers.
14///
15/// Routes all output to a `pre` on the page currently. Eventually this probably
16/// wants to be a pretty table with colors and folding and whatnot.
17pub struct Worker {}
18
19#[wasm_bindgen]
20extern "C" {
21    type WorkerError;
22    #[wasm_bindgen(method, getter, structural)]
23    fn stack(this: &WorkerError) -> JsValue;
24
25    #[wasm_bindgen(js_name = "__wbg_test_output_writeln")]
26    fn write_output_line(data: JsValue);
27}
28
29impl Worker {
30    /// Attempts to create a new formatter for web worker
31    pub fn new() -> Worker {
32        Worker {}
33    }
34}
35
36impl super::Formatter for Worker {
37    fn writeln(&self, line: &str) {
38        write_output_line(JsValue::from(String::from(line)));
39    }
40
41    fn log_test(&self, name: &str, result: &TestResult) {
42        self.writeln(&format!("test {} ... {}", name, result));
43    }
44
45    fn stringify_error(&self, err: &JsValue) -> String {
46        // TODO: this should be a checked cast to `Error`
47        let error = Error::from(err.clone());
48        let name = String::from(error.name());
49        let message = String::from(error.message());
50        let err = WorkerError::from(err.clone());
51        let stack = err.stack();
52
53        let header = format!("{}: {}", name, message);
54        let stack = match stack.as_string() {
55            Some(stack) => stack,
56            None => return header,
57        };
58
59        // If the `stack` variable contains the name/message already, this is
60        // probably a chome-like error which is already rendered well, so just
61        // return this info
62        if stack.contains(&header) {
63            return stack;
64        }
65
66        // Fallback to make sure we don't lose any info
67        format!("{}\n{}", header, stack)
68    }
69}