ShadowRealmTests.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using Jint.Native.Object;
  2. namespace Jint.Tests.PublicInterface;
  3. public class ShadowRealmTests
  4. {
  5. [Fact]
  6. public void CanUseViaEngineMethods()
  7. {
  8. var engine = new Engine(options => options.EnableModules(GetBasePath()));
  9. var shadowRealm = engine.Realm.Intrinsics.ShadowRealm.Construct();
  10. // lexically scoped (let/const) are visible during single call
  11. Assert.Equal(123, shadowRealm.Evaluate("const s = 123; const f = () => s; f();"));
  12. Assert.Equal(true, shadowRealm.Evaluate("typeof f === 'undefined'"));
  13. // vars hold longer
  14. Assert.Equal(456, shadowRealm.Evaluate("function foo() { return 456; }; foo();"));
  15. Assert.Equal(456, shadowRealm.Evaluate("foo();"));
  16. // not visible in global engine though
  17. Assert.Equal(true, engine.Evaluate("typeof foo === 'undefined'"));
  18. // modules
  19. var importValue = shadowRealm.ImportValue("./modules/format-name.js", "formatName");
  20. var formatName = (ObjectInstance) importValue.UnwrapIfPromise();
  21. var result = engine.Invoke(formatName, "John", "Doe").AsString();
  22. Assert.Equal("John Doe", result);
  23. }
  24. private static string GetBasePath()
  25. {
  26. var assemblyDirectory = new DirectoryInfo(AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory);
  27. var current = assemblyDirectory;
  28. while (current is not null && current.GetDirectories().All(x => x.Name != "Jint.Tests"))
  29. {
  30. current = current.Parent;
  31. }
  32. if (current is null)
  33. {
  34. throw new NullReferenceException($"Could not find tests base path, assemblyPath: {assemblyDirectory}");
  35. }
  36. return Path.Combine(current.FullName, "Jint.Tests", "Runtime", "Scripts");
  37. }
  38. }