You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. var thunkify = require('..');
  2. var assert = require('assert');
  3. var fs = require('fs');
  4. describe('thunkify(fn)', function(){
  5. it('should work when sync', function(done){
  6. function read(file, fn) {
  7. fn(null, 'file: ' + file);
  8. }
  9. read = thunkify(read);
  10. read('foo.txt')(function(err, res){
  11. assert(!err);
  12. assert('file: foo.txt' == res);
  13. done();
  14. });
  15. })
  16. it('should work when async', function(done){
  17. function read(file, fn) {
  18. setTimeout(function(){
  19. fn(null, 'file: ' + file);
  20. }, 5);
  21. }
  22. read = thunkify(read);
  23. read('foo.txt')(function(err, res){
  24. assert(!err);
  25. assert('file: foo.txt' == res);
  26. done();
  27. });
  28. })
  29. it('should maintain the receiver', function(done){
  30. function load(fn) {
  31. fn(null, this.name);
  32. }
  33. var user = {
  34. name: 'tobi',
  35. load: thunkify(load)
  36. };
  37. user.load()(function(err, name){
  38. if (err) return done(err);
  39. assert('tobi' == name);
  40. done();
  41. });
  42. })
  43. it('should catch errors', function(done){
  44. function load(fn) {
  45. throw new Error('boom');
  46. }
  47. load = thunkify(load);
  48. load()(function(err){
  49. assert(err);
  50. assert('boom' == err.message);
  51. done();
  52. });
  53. })
  54. it('should ignore multiple callbacks', function(done){
  55. function load(fn) {
  56. fn(null, 1);
  57. fn(null, 2);
  58. fn(null, 3);
  59. }
  60. load = thunkify(load);
  61. load()(done);
  62. })
  63. it('should pass all results', function(done){
  64. function read(file, fn) {
  65. setTimeout(function(){
  66. fn(null, file[0], file[1]);
  67. }, 5);
  68. }
  69. read = thunkify(read);
  70. read('foo.txt')(function(err, a, b){
  71. assert(!err);
  72. assert('f' == a);
  73. assert('o' == b);
  74. done();
  75. });
  76. })
  77. it('should work with node methods', function(done){
  78. fs.readFile = thunkify(fs.readFile);
  79. fs.readFile('package.json')(function(err, buf){
  80. assert(!err);
  81. assert(Buffer.isBuffer(buf));
  82. fs.readFile('package.json', 'utf8')(function(err, str){
  83. assert(!err);
  84. assert('string' == typeof str);
  85. done();
  86. });
  87. });
  88. })
  89. })