简体   繁体   中英

Unit test using sinon with promises

I have a function returning a Promise wrapped around another function that works with it's own implementation of the promises/callbacks, like so:

function getResult() {
  return new Promise((resolve, reject) => {
   const service = Service(config)
    return Service.initialize({scope: 'param'})
      .success((result) => {
        result ? resolve(service.res) : reject(new Error('Something happened'))
      })
      .error(() => {
        reject(new Error('Something happened'))
      )})
  })
}

EDIT : I can re-write the above function to something like:

function getResult(done) {
 const service = Service(config)
  Service.initialize({scope: 'param'})
   .success((result) => {
     result ? done(null, result) : done(new Error('Something happened'), null))
   })
   .error(() => {
     done(new Error('Something happened'), null)
   }

I don't know how can I unit test something like this? I tried to stub the Service and use sinon to check if it was called, but the following didn't work:

it('should initialize service and return res', () => {
    const mockService = sinon.stub(Service, 'initialize')
    mockService.withArgs({scope: 'param'}).returns(Promise.resolve(true))

    expect(mockService.callCount).to.equal(1)
  })

Any help would be appreciated.

You are just checking if it is called, so no need to wait for anything.

it('should initialize service and return res', () => {
    const mockService = sinon.stub(Service, 'initialize')
    mockService.withArgs({scope: 'param'}).returns(Promise.resolve(true))

    getResult()

    expect(mockService.callCount).to.equal(1)
  })

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