jsunit-goodies.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /* appjet:version 0.1 */
  2. /* appjet:library */
  3. // Copyright (c) 2010, Herbert Vojčík
  4. // Licensed by MIT license (http://www.opensource.org/licenses/mit-license.php)
  5. /**@overview This library contains various utility functions to support unit-testing.
  6. */
  7. /**
  8. * Returns stub function that logs arguments called
  9. * into its property called log and returns retval.
  10. * Useful primarily for testing.
  11. */
  12. function stub(retval) {
  13. var result = function() {
  14. result.log.push(Array.slice(arguments));
  15. return retval;
  16. };
  17. result.log = [];
  18. return result;
  19. }
  20. function picker () {
  21. var args = Array.prototype.slice.call(arguments);
  22. return function (self) {
  23. return args.map(function (prop) {
  24. var ch = prop[0], rest = prop.substring(1);
  25. return ch === "+" ? +self[rest] : ch === "?" ? !!self[rest] : self[prop];
  26. });
  27. };
  28. };
  29. function mockLib(lib, exports) {
  30. var old = appjet._native.importApp;
  31. appjet._native.importApp = function () { return exports; };
  32. try { import({}, lib); } finally { appjet._native.importApp = old; }
  33. }
  34. /* appjet:server */
  35. import("lib-support/jsunit");
  36. var _l = import({}, "lib-support/jsunit-goodies");
  37. // ==== Test cases ====
  38. page.testSuite = [
  39. function logIsEmptyForNewStub() {
  40. var f = _l.stub();
  41. assertArrayEquals("Log is not empty array", [], f.log);
  42. },
  43. function stubIsAFunction() {
  44. var f = _l.stub();
  45. assertEquals("Stub is not a function", "function", typeof f);
  46. },
  47. function stubWithoutRetvalReturnsUndefined() {
  48. var f = _l.stub();
  49. assertEquals("Stub doesn't return undefined", undefined, f(3, "hello"));
  50. },
  51. function stubWithRetvalReturnsRetval() {
  52. var f = _l.stub("world");
  53. assertEquals("Stub returns incorrect value", "world", f(3, "hello"));
  54. },
  55. function stub_CalledMultipleTimes_ReturnsAlwaysRetval_AndLogsArguments() {
  56. var f = _l.stub("hi");
  57. var r1 = f("hello", 14, "world");
  58. assertArrayEquals("Log is incorrect 1", [["hello", 14, "world"]], f.log);
  59. var r2 = f("!", f);
  60. assertArrayEquals("Log is incorrect 2", [["hello", 14, "world"], ["!", f]], f.log);
  61. f();
  62. assertArrayEquals("Log is incorrect 3", [["hello", 14, "world"], ["!", f], []], f.log);
  63. assertEquals("Stub returns incorrect value 1", "hi", r1);
  64. assertEquals("Stub returns incorrect value 2", "hi", r2);
  65. },
  66. //TODO tests for the rest
  67. ];
  68. // ==== Test runner ====
  69. import("lib-support/runner");
  70. runTestsByDefault();