wasm-bindgen/tests/wasm/jscast.rs
Alex Crichton 11553a1af2 Implement JsCast for all imported types
This commit implements the `JsCast` trait automatically for all imported types
in `#[wasm_bindgen] extern { ... }` blocks. The main change here was to generate
an `instanceof` shim for all imported types in case it's needed.

All imported types now also implement `AsRef<JsValue>` and `AsMut<JsValue>`
2018-08-07 12:59:51 -07:00

69 lines
1.7 KiB
Rust

use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
use wasm_bindgen_test::*;
#[wasm_bindgen(module = "tests/wasm/jscast.js", version = "*")]
extern {
type JsCast1;
#[wasm_bindgen(constructor)]
fn new() -> JsCast1;
#[wasm_bindgen(method)]
fn myval(this: &JsCast1) -> u32;
type JsCast2;
#[wasm_bindgen(constructor)]
fn new() -> JsCast2;
type JsCast3;
#[wasm_bindgen(constructor)]
fn new() -> JsCast3;
}
#[wasm_bindgen_test]
fn instanceof_works() {
let a = JsCast1::new();
let b = JsCast2::new();
let c = JsCast3::new();
assert!(a.is_instance_of::<JsCast1>());
assert!(!a.is_instance_of::<JsCast2>());
assert!(!a.is_instance_of::<JsCast3>());
assert!(!b.is_instance_of::<JsCast1>());
assert!(b.is_instance_of::<JsCast2>());
assert!(!b.is_instance_of::<JsCast3>());
assert!(c.is_instance_of::<JsCast1>());
assert!(!c.is_instance_of::<JsCast2>());
assert!(c.is_instance_of::<JsCast3>());
}
#[wasm_bindgen_test]
fn casting() {
let a = JsCast1::new();
let b = JsCast2::new();
let c = JsCast3::new();
assert!(a.dyn_ref::<JsCast1>().is_some());
assert!(a.dyn_ref::<JsCast2>().is_none());
assert!(a.dyn_ref::<JsCast3>().is_none());
assert!(b.dyn_ref::<JsCast1>().is_none());
assert!(b.dyn_ref::<JsCast2>().is_some());
assert!(b.dyn_ref::<JsCast3>().is_none());
assert!(c.dyn_ref::<JsCast1>().is_some());
assert!(c.dyn_ref::<JsCast2>().is_none());
assert!(c.dyn_ref::<JsCast3>().is_some());
}
#[wasm_bindgen_test]
fn method_calling() {
let a = JsCast1::new();
let b = JsCast3::new();
assert_eq!(a.myval(), 1);
assert_eq!(b.dyn_ref::<JsCast1>().unwrap().myval(), 3);
assert_eq!(b.unchecked_ref::<JsCast1>().myval(), 3);
}