如何在使用 sinon 的 mocha 单元测试中正确剔除请求承诺?

How to properly stub out request-promise in a mocha unit test using sinon?

我的单元测试是:

describe.only("Validator Service Tests", function () {
  let request
  before((done) => {
    request = sinon.stub()

    done()
  })

  beforeEach(() => {
    process.env.API_URL = "http://test"
  })

  it('Should return with no errors if the file matches the schema', () => {
    const updateStatusSpy = sinon.spy(FileLib, 'updateStatus')
    request.yields({message: 'ok'})

    return ValidatorService.handleMessage({
      file: 'test'
    })
    .then((response) => {
      assert()
      console.log(response)
      sinon.assert.calledOnce(updateStatusSpy)
      assert(response, 'f')
    })
  })

})

问题是我的 handleMessage 函数,它看起来像:

exports.handleMessage = (message, done) => {
  return stuff()
  .then((result) => {
    console.log('result', result)
    if(result) {
      return FileLib.updateStatus(fileId, 'valid')
    }
    return FileLib.updateStatus(fileId, 'invalid')
  })
  .then(done)
}

还有我的 updateStatus 函数:

exports.updateStatus = function(fileId, status) {
  console.log(fileId, status)
  return request.put({
    uri: `${process.env.API_URL}/stuff/${fileId}`,
    body: {
      status: status
    }
  })
}

我的实际request调用被埋得这么深,测试时如何将其存根?

我不确定我是否完全理解你的问题,但如果你只是想存根,请尝试这样的事情:

let stub;

beforeEach(() => {
    putStub = sinon.stub(request, 'put').resolves('some_val_or_object'); //or yields or callsFake, depending on what you're using
});

it('should call request with put', async () => {
    await //call your code

    expect(putStub.called).to.be.true;
    expect(putStub.calledWith(whatever_you_want_to_check)).to.be.true;
});