JavascriptEvaluationTests.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Threading.Tasks;
  3. using NUnit.Framework;
  4. namespace CefGlue.Tests.Javascript
  5. {
  6. public class JavascriptEvaluationTests : TestBase
  7. {
  8. class Person
  9. {
  10. public string Name = null;
  11. public int Age = 0;
  12. }
  13. protected async override Task ExtraSetup()
  14. {
  15. await Browser.LoadContent("<script></script>");
  16. await base.ExtraSetup();
  17. }
  18. [Test]
  19. public async Task NumberReturn()
  20. {
  21. var result = await EvaluateJavascript<int>("return 1+1;");
  22. Assert.AreEqual(2, result);
  23. }
  24. [Test]
  25. public async Task StringReturn()
  26. {
  27. const string Result = "this is a test";
  28. var result = await EvaluateJavascript<string>($"return '{Result}';");
  29. Assert.AreEqual(Result, result);
  30. }
  31. [Test]
  32. public async Task ListReturn()
  33. {
  34. var result = await EvaluateJavascript<int[]>("return [1, 2, 3];");
  35. CollectionAssert.AreEqual(new[] { 1, 2, 3 }, result);
  36. }
  37. [Test]
  38. public async Task DynamicObjectReturn()
  39. {
  40. var result = await EvaluateJavascript<dynamic>("return { 'foo': 'foo-value', 'bar': 10, 'baz': [1, 2] }");
  41. Assert.AreEqual("foo-value", result.foo);
  42. Assert.AreEqual(10, result.bar);
  43. CollectionAssert.AreEqual(new [] { 1, 2 }, result.baz);
  44. }
  45. [Test]
  46. public async Task ObjectReturn()
  47. {
  48. var result = await EvaluateJavascript<Person>("return { 'Name': 'cef', 'Age': 10 }");
  49. Assert.AreEqual("cef", result.Name);
  50. Assert.AreEqual(10, result.Age);
  51. }
  52. [Test]
  53. public void ExceptionThrown()
  54. {
  55. const string ExceptionMessage = "ups";
  56. var exception = Assert.ThrowsAsync<Exception>(async () => await EvaluateJavascript<string>($"throw new Error('{ExceptionMessage}')"));
  57. StringAssert.Contains(ExceptionMessage, exception.Message);
  58. }
  59. [Test]
  60. public void CancelledOnTimeout()
  61. {
  62. var timeout = TimeSpan.FromMilliseconds(500);
  63. Assert.ThrowsAsync<TaskCanceledException>(async () => await EvaluateJavascript<string>($"var start = new Date(); while((new Date() - start) < ({timeout.TotalMilliseconds} + 200));", timeout));
  64. }
  65. [Test]
  66. public async Task NotCancelledBeforeTimeout()
  67. {
  68. var timeout = TimeSpan.FromMilliseconds(500);
  69. var result = await EvaluateJavascript<int>($"return 1;", timeout);
  70. Assert.AreEqual(1, result);
  71. }
  72. }
  73. }