mirror of https://github.com/boa-dev/boa.git
Browse Source
* Add functions to create modules from a JSON value * Move json_module to Module::from_value_as_default * Flag the whole json module behind the json feature * Rename and add docpull/3812/head
Hans Larsen
9 months ago
committed by
GitHub
2 changed files with 102 additions and 0 deletions
@ -0,0 +1,65 @@
|
||||
#![allow(unused_crate_dependencies, missing_docs)] |
||||
|
||||
use std::rc::Rc; |
||||
|
||||
use boa_engine::builtins::promise::PromiseState; |
||||
use boa_engine::module::{ModuleLoader, Referrer}; |
||||
use boa_engine::{js_string, Context, JsResult, JsString, Module, Source}; |
||||
|
||||
#[test] |
||||
fn test_json_module_from_str() { |
||||
struct TestModuleLoader(JsString); |
||||
impl ModuleLoader for TestModuleLoader { |
||||
fn load_imported_module( |
||||
&self, |
||||
_referrer: Referrer, |
||||
specifier: JsString, |
||||
finish_load: Box<dyn FnOnce(JsResult<Module>, &mut Context)>, |
||||
context: &mut Context, |
||||
) { |
||||
assert_eq!(specifier.to_std_string_escaped(), "basic"); |
||||
|
||||
finish_load( |
||||
Ok(Module::parse_json(self.0.clone(), context).unwrap()), |
||||
context, |
||||
); |
||||
} |
||||
} |
||||
|
||||
let json_string = js_string!(r#"{"key":"value","other":123}"#); |
||||
let mut context = Context::builder() |
||||
.module_loader(Rc::new(TestModuleLoader(json_string.clone()))) |
||||
.build() |
||||
.unwrap(); |
||||
|
||||
let source = Source::from_bytes( |
||||
b" |
||||
import basic_json from 'basic'; |
||||
export let json = basic_json; |
||||
", |
||||
); |
||||
|
||||
let module = Module::parse(source, None, &mut context).unwrap(); |
||||
let promise = module.load_link_evaluate(&mut context); |
||||
context.run_jobs(); |
||||
|
||||
match promise.state() { |
||||
PromiseState::Pending => {} |
||||
PromiseState::Fulfilled(v) => { |
||||
assert!(v.is_undefined()); |
||||
} |
||||
PromiseState::Rejected(e) => { |
||||
panic!("Unexpected error: {:?}", e.to_string(&mut context).unwrap()); |
||||
} |
||||
} |
||||
|
||||
let json = module |
||||
.namespace(&mut context) |
||||
.get(js_string!("json"), &mut context) |
||||
.unwrap(); |
||||
|
||||
assert_eq!( |
||||
JsString::from(json.to_json(&mut context).unwrap().to_string()), |
||||
json_string |
||||
); |
||||
} |
Loading…
Reference in new issue