run.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. var assert = require("assert");
  2. var makeAccessor = require("../private").makeAccessor;
  3. var acc1 = makeAccessor();
  4. var obj = {};
  5. var hasOwn = obj.hasOwnProperty;
  6. acc1(obj).foo = 42;
  7. assert.deepEqual(obj, {});
  8. assert.deepEqual(acc1(obj), { foo: 42 });
  9. assert.deepEqual(acc1(acc1(obj)), {});
  10. assert.deepEqual(acc1(obj), { foo: 42 });
  11. assert.deepEqual(Object.keys(acc1(obj)), ["foo"]);
  12. assert.strictEqual(Object.getOwnPropertyNames(acc1(obj)).length, 1);
  13. assert.strictEqual(Object.getOwnPropertyNames(acc1(acc1(obj))).length, 0);
  14. acc1(obj).bar = "baz";
  15. assert.deepEqual(acc1(obj), { foo: 42, bar: "baz" });
  16. delete acc1(obj).foo;
  17. assert.deepEqual(acc1(obj), { bar: "baz" });
  18. try {
  19. acc1(42);
  20. throw new Error("threw wrong error");
  21. } catch (err) {
  22. assert.ok(err);
  23. }
  24. var acc2 = makeAccessor();
  25. assert.notStrictEqual(acc1, acc2);
  26. assert.notStrictEqual(acc1(obj), acc2(obj));
  27. assert.deepEqual(acc2(obj), {});
  28. assert.strictEqual(Object.getOwnPropertyNames(obj).length, 0);
  29. assert.strictEqual(Object.keys(obj).length, 0);
  30. acc2(obj).bar = "asdf";
  31. assert.deepEqual(acc2(obj), { bar: "asdf" });
  32. acc2.forget(obj);
  33. acc2(obj).bar = "asdf";
  34. var oldSecret = acc2(obj);
  35. assert.strictEqual(oldSecret.bar, "asdf");
  36. acc2.forget(obj);
  37. var newSecret = acc2(obj);
  38. assert.notStrictEqual(oldSecret, newSecret);
  39. assert.ok(hasOwn.call(oldSecret, "bar"));
  40. assert.ok(!hasOwn.call(newSecret, "bar"));
  41. newSecret.bar = "zxcv";
  42. assert.strictEqual(oldSecret.bar, "asdf");
  43. assert.strictEqual(acc2(obj).bar, "zxcv");
  44. function creatorFn(object) {
  45. return { self: object };
  46. }
  47. var acc3 = makeAccessor(creatorFn);
  48. acc3(obj).xxx = "yyy";
  49. assert.deepEqual(acc3(obj), {
  50. self: obj,
  51. xxx: "yyy"
  52. });
  53. acc3.forget(obj);
  54. assert.deepEqual(acc3(obj), {
  55. self: obj
  56. });
  57. var green = "\033[32m";
  58. var reset = "\033[0m";
  59. console.log(green + "ALL PASS" + reset);