test.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. var tape = require('tape')
  2. var thunky = require('./')
  3. tape('run only once', function (t) {
  4. t.plan(3)
  5. var ran = 0
  6. var run = thunky(function (cb) {
  7. ran++
  8. cb()
  9. })
  10. run(function () {
  11. t.same(ran, 1, 'ran once')
  12. })
  13. run(function () {
  14. t.same(ran, 1, 'ran once')
  15. })
  16. run(function () {
  17. t.same(ran, 1, 'ran once')
  18. })
  19. })
  20. tape('run only once async', function (t) {
  21. t.plan(3)
  22. var ran = 0
  23. var run = thunky(function (cb) {
  24. process.nextTick(function () {
  25. ran++
  26. cb()
  27. })
  28. })
  29. run(function () {
  30. t.same(ran, 1, 'ran once')
  31. })
  32. run(function () {
  33. t.same(ran, 1, 'ran once')
  34. })
  35. run(function () {
  36. t.same(ran, 1, 'ran once')
  37. })
  38. })
  39. tape('re-run on error', function (t) {
  40. t.plan(3)
  41. var ran = 0
  42. var run = thunky(function (cb) {
  43. ran++
  44. cb(new Error('stop'))
  45. })
  46. run(function () {
  47. t.same(ran, 1, 'ran once')
  48. run(function () {
  49. t.same(ran, 2, 'ran once')
  50. run(function () {
  51. t.same(ran, 3, 'ran once')
  52. })
  53. })
  54. })
  55. })
  56. tape('pass arguments', function (t) {
  57. t.plan(6)
  58. var ran = 0
  59. var run = thunky(function (fn) {
  60. ran++
  61. fn({ hello: 'world' })
  62. })
  63. run(function (val) {
  64. t.same(ran, 1, 'ran once')
  65. t.same(val, { hello: 'world' })
  66. run(function (val) {
  67. t.same(ran, 1, 'ran once')
  68. t.same(val, { hello: 'world' })
  69. run(function (val) {
  70. t.same(ran, 1, 'ran once')
  71. t.same(val, { hello: 'world' })
  72. })
  73. })
  74. })
  75. })
  76. tape('callback is optional', function (t) {
  77. t.plan(2)
  78. var ran = 0
  79. var run = thunky(function (fn) {
  80. ran++
  81. fn({ hello: 'world' })
  82. })
  83. run()
  84. run(function (val) {
  85. t.same(ran, 1, 'ran once')
  86. t.same(val, { hello: 'world' })
  87. })
  88. })
  89. tape('always async', function (t) {
  90. t.plan(2)
  91. var run = thunky(function (cb) {
  92. process.nextTick(cb)
  93. })
  94. var sync = true
  95. run(function () {
  96. t.ok(!sync, 'not sync')
  97. var innerSync = true
  98. run(function () {
  99. t.ok(!innerSync, 'not sync')
  100. })
  101. innerSync = false
  102. })
  103. sync = false
  104. })