FunctionToStringTest.cs 1.1 KB

1234567891011121314151617181920212223242526
  1. using FluentAssertions;
  2. namespace Jint.Tests.PublicInterface;
  3. public class FunctionToStringTest
  4. {
  5. [Fact]
  6. public void CanRegisterCustomFunctionToString()
  7. {
  8. const string Code = "var x = 1; var y = 3; function testFunction() { return 'Something'; }; testFunction.toString(); var z = x + y;";
  9. // we can rewrite back with AST to get custom formatting
  10. var engine = new Engine(options =>
  11. options.Host.FunctionToStringHandler = (function, node) => node.ToJavaScript(KnRJavaScriptTextFormatterOptions.Default)
  12. );
  13. engine.Evaluate(Code).AsString().Should().Be($"function testFunction() {{{Environment.NewLine} return 'Something';{Environment.NewLine}}}");
  14. // or we can brute force the original input when we use node's location information
  15. engine = new Engine(options =>
  16. options.Host.FunctionToStringHandler = (function, node) => Code.Substring(node.Start, node.End - node.Start)
  17. );
  18. engine.Evaluate(Code).AsString().Should().Be("function testFunction() { return 'Something'; }");
  19. }
  20. }