Guest User

Untitled

a guest
Jul 19th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. ### Given an api that looks like this:
  2.  
  3. ```javascript
  4. this.client = redis.createClient()
  5.  
  6. const asyncSet = promisify(this.client.set).bind(this.client)
  7.  
  8. return asyncSet(key, value, "EX", expiry)
  9. ```
  10.  
  11.  
  12. ### The correct corresponding mock looks like:
  13.  
  14. ```javascript
  15. jest.mock('redis', () => ({
  16. createClient: jest.fn(() => ({
  17. set: jest.fn((a, b, c, d, callback) => callback(null, true))
  18. }))
  19. }))
  20. ```
  21.  
  22. ## How promisify works:
  23.  
  24. Given an function that normally takes a callback as the LAST parameter:
  25.  
  26. ```javascript
  27. function(a,b,c,d,callback){
  28. //do some async thing
  29.  
  30. callback(null, "I'm done!") //success response
  31. OR
  32. callback("ERROR'd", null) //error response
  33. }
  34. ```
  35.  
  36. So the overly simplified "promisify'd" code might look like:
  37.  
  38. ```javascript
  39. const promise = new Promise()
  40.  
  41. function(a,b,c,d,callback){
  42. //do some async thing
  43.  
  44. if(<first callback argument is set>){
  45. promise.resolve("I'm done!")
  46. }else{
  47. promise.reject("ERROR'd")
  48. }
  49.  
  50. }
  51. return promise
  52. ```
Add Comment
Please, Sign In to add comment