Skip to content

Instantly share code, notes, and snippets.

@alex-hall
Last active December 29, 2022 17:07
Show Gist options
  • Save alex-hall/e2ba1c366331e35a721e4bbe72df2a65 to your computer and use it in GitHub Desktop.
Save alex-hall/e2ba1c366331e35a721e4bbe72df2a65 to your computer and use it in GitHub Desktop.
How to mock a promisify'd method

Given an api that looks like this:

    this.client = redis.createClient()
    
    const asyncSet = promisify(this.client.set).bind(this.client)

    return asyncSet(key, value, "EX", expiry)

The correct corresponding mock looks like:

    jest.mock('redis', () => ({
        createClient: jest.fn(() => ({
            set: jest.fn((a, b, c, d, callback) => callback(null, true))
        }))
    }))

How promisify works:

Given an function that normally takes a callback as the LAST parameter:

  function(a,b,c,d,callback){
    //do some async thing
    
    callback(null, "I'm done!") //success response
    OR
    callback("ERROR'd", null) //error response
  }

So the overly simplified "promisify'd" code might look like:

   const promise = new Promise()  
    
   function(a,b,c,d,callback){
    //do some async thing
    
      if(<first callback argument is set>){
        promise.reject("ERROR'd")
      }else{
        promise.resolve("I'm done!")
      }
   }
  return promise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment