SyncBailHook.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. require("babel-polyfill");
  7. const SyncBailHook = require("../SyncBailHook");
  8. describe("SyncBailHook", () => {
  9. it("should allow to create sync bail hooks", async () => {
  10. const h1 = new SyncBailHook(["a"]);
  11. const h2 = new SyncBailHook(["a", "b"]);
  12. const h3 = new SyncBailHook(["a"]);
  13. let r = h1.call(1);
  14. expect(r).toEqual(undefined);
  15. h1.tap("A", (a) => undefined);
  16. h2.tap("A", (a, b) => [a, b]);
  17. expect(h1.call(1)).toEqual(undefined);
  18. expect(await h1.promise(1)).toEqual(undefined);
  19. expect(await pify(cb => h1.callAsync(1, cb))).toEqual(undefined);
  20. expect(h2.call(1, 2)).toEqual([1, 2]);
  21. expect(await h2.promise(1, 2)).toEqual([1, 2]);
  22. expect(await pify(cb => h2.callAsync(1, 2, cb))).toEqual([1, 2]);
  23. h1.tap("B", (a) => "ok" + a);
  24. h2.tap("B", (a, b) => "wrong");
  25. expect(h1.call(10)).toEqual("ok10");
  26. expect(await h1.promise(10)).toEqual("ok10");
  27. expect(await pify(cb => h1.callAsync(10, cb))).toEqual("ok10");
  28. expect(h2.call(10, 20)).toEqual([10, 20]);
  29. expect(await h2.promise(10, 20)).toEqual([10, 20]);
  30. expect(await pify(cb => h2.callAsync(10, 20, cb))).toEqual([10, 20]);
  31. });
  32. it("should allow to intercept calls", () => {
  33. const hook = new SyncBailHook(["x"]);
  34. const mockCall = jest.fn();
  35. const mockTap = jest.fn(x => x);
  36. hook.intercept({
  37. call: mockCall,
  38. tap: mockTap
  39. });
  40. hook.call(5);
  41. expect(mockCall).toHaveBeenLastCalledWith(5);
  42. expect(mockTap).not.toHaveBeenCalled();
  43. hook.tap("test", () => 10);
  44. hook.call(7);
  45. expect(mockCall).toHaveBeenLastCalledWith(7);
  46. expect(mockTap).toHaveBeenCalled();
  47. });
  48. });
  49. function pify(fn) {
  50. return new Promise((resolve, reject) => {
  51. fn((err, result) => {
  52. if(err)
  53. reject(err);
  54. else
  55. resolve(result);
  56. });
  57. });
  58. }