简体   繁体   中英

How to mock objects which return a promise?

I want to create a mock of this object for unit testing purposes.

sqs.listQueues().promise()
      .then(...

Here's one of my attempts at mocking this and still getting the error sqs.listQueues(...).promise is not a function

const sqs = {
    listQueues: () => Promise.resolve(this),
    promise: () => Promise.resolve()
  }

How can i properly mock this object?

Looks like listQueues() should not return a promise. Maybe this would work:

const sqs = {
  listQueues: () => ({
    promise: () => Promise.resolve()
  })
}

Here's a fairly naive version that might get you going.

 const mockResolve = (val, delay = 0) => () => new Promise((res) => setTimeout(() => res(val), delay)) const mockReject = (err, delay = 0) => () => new Promise((_, rej) => setTimeout(() => rej(err), delay)) const sqs = { listQueues: () => ({ promise: mockResolve('foo') }) } sqs.listQueues().promise().then(console.log) 

There are probably many things wrong with this, but it's only meant as a first pass.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM