Shamoon
Shamoon

Reputation: 43501

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

My unit test is:

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')
    })
  })

})

The problem is my handleMessage function, which looks like:

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)
}

And my updateStatus function:

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

My actual request call is buried so deep in, how can I stub it out when testing?

Upvotes: 0

Views: 2833

Answers (1)

Mankind1023
Mankind1023

Reputation: 7732

I'm not sure I completely understand your question, but if you are just trying to stub put, try something like this:

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;
});

Upvotes: 2

Related Questions