单元测试嵌套的promise会因超时而失败

时间:2016-04-26 18:12:56

标签: javascript unit-testing promise mocha

我有一个围绕Axios XHR库的包装器,我正在尝试为我的代码编写一些单元测试。但是,当我运行我的测试时,他们都没有告诉我超时超时。我如何构建我的测试以运行我的断言?

这是包装代码:

export const clientRequest = (xhrClient, endpoint, params = {}) => {
  const method = params.method || 'get'
  const {config, data, noOrg, unrestricted} = params

  let reqParams = data
  if (!isNil(data) && method === 'get') {
    reqParams = {params: data}
  }

  const authConfig = unrestricted ? {...config, withCredentials: false} :
    {...config, withCredentials: true}

  const concatEndpoint = noOrg ? endpoint :
    `${Cookies.get('organization') || 'default' }${endpoint}`

  return new Promise((resolve, reject) => {
    xhrClient[method](concatEndpoint, reqParams, authConfig)
      .then(response => resolve(response))
      .catch(err => reject(err))
  })
}

有问题的测试:

  describe('clientRequest()', () => {
    const resolveSpy = sinon.spy()
    const fakeClient = {
      get: () => new Promise(resolveSpy),
    }

    it.only('should make a call to the supplied method', (done) => {
      const result = xhr.clientRequest(fakeClient, '/foobar', {method: 'get'})
      result.then(() => {
        expect(resolveSpy).to.have.beenCalledWith('/foobar', undefined, {withCredentials: true})
        done()
      })
    })
  })

2 个答案:

答案 0 :(得分:0)

似乎fakeClient.get永远不会解决。

由于这是应该监视的方法,我建议以这种方式更改fakeClient

const fakeClient = {
  get: () => Promise.resolve()
}
sinon.spy(fakeClient, 'get');

为了处理承诺链中的错误,添加catch调用也很重要:

result.then(() => {
  expect(resolveSpy).to.have.beenCalledWith('/foobar', undefined, {withCredentials: true})
  done()
}).catch(done);

答案 1 :(得分:0)

我最终关注@MarcoL的建议,并回复了期望。

it('should make a call to the supplied method', () => {
  const result = xhr.clientRequest(fakeClient, '/foobar', {method: 'get'})
  return result.then(() => (
    expect(resolveSpy).to.have.been.calledWith('/foobar', undefined, {withCredentials: true})
  ))
})