FunctionTests.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using Jint.Native;
  3. using Jint.Runtime;
  4. using Jint.Runtime.Interop;
  5. using Xunit;
  6. namespace Jint.Tests.Runtime
  7. {
  8. public class FunctionTests
  9. {
  10. [Fact]
  11. public void BindCombinesBoundArgumentsToCallArgumentsCorrectly()
  12. {
  13. var e = new Engine();
  14. e.Execute("var testFunc = function (a, b, c) { return a + ', ' + b + ', ' + c + ', ' + JSON.stringify(arguments); }");
  15. Assert.Equal("a, 1, a, {\"0\":\"a\",\"1\":1,\"2\":\"a\"}", e.Execute("testFunc('a', 1, 'a');").GetCompletionValue().AsString());
  16. Assert.Equal("a, 1, a, {\"0\":\"a\",\"1\":1,\"2\":\"a\"}", e.Execute("testFunc.bind('anything')('a', 1, 'a');").GetCompletionValue().AsString());
  17. }
  18. [Fact]
  19. public void ProxyCanBeRevokedWithoutContext()
  20. {
  21. new Engine()
  22. .Execute(@"
  23. var revocable = Proxy.revocable({}, {});
  24. var revoke = revocable.revoke;
  25. revoke.call(null);
  26. ");
  27. }
  28. [Fact]
  29. public void ArrowFunctionShouldBeExtensible()
  30. {
  31. new Engine()
  32. .SetValue("assert", new Action<bool>(Assert.True))
  33. .Execute(@"
  34. var a = () => null
  35. Object.defineProperty(a, 'hello', { enumerable: true, get: () => 'world' })
  36. assert(a.hello === 'world')
  37. a.foo = 'bar';
  38. assert(a.foo === 'bar');
  39. ");
  40. }
  41. [Fact]
  42. public void BlockScopeFunctionShouldWork()
  43. {
  44. const string script = @"
  45. function execute(doc, args){
  46. var i = doc;
  47. {
  48. function doSomething() {
  49. return 'ayende';
  50. }
  51. i.Name = doSomething();
  52. }
  53. }
  54. ";
  55. var engine = new Engine(options =>
  56. {
  57. options.Strict();
  58. });
  59. engine.Execute(script);
  60. var obj = engine.Execute("var obj = {}; execute(obj); return obj;").GetCompletionValue().AsObject();
  61. Assert.Equal("ayende", obj.Get("Name").AsString());
  62. }
  63. [Fact]
  64. public void ObjectCoercibleForCallable()
  65. {
  66. const string script = @"
  67. var booleanCount = 0;
  68. Boolean.prototype.then = function() {
  69. booleanCount += 1;
  70. };
  71. function test() {
  72. this.then();
  73. }
  74. testFunction.call(true);
  75. assertEqual(booleanCount, 1);
  76. ";
  77. var engine = new Engine();
  78. engine
  79. .SetValue("testFunction", new ClrFunctionInstance(engine, "testFunction", (thisValue, args) =>
  80. {
  81. return engine.Invoke(thisValue, "then", new[] { Undefined.Instance, args.At(0) });
  82. }))
  83. .SetValue("assertEqual", new Action<object, object>((a, b) => Assert.Equal(b, a)))
  84. .Execute(script);
  85. }
  86. }
  87. }