MadsRC
MadsRC

Reputation: 197

Testing that function is called with parameter in a Promise

Given these 2 functions

function func1() {
  return new Promise((resolve, reject) => {
    return resolve({
      method: function(variable) {
        return variable
      }
    })
  })
}

function func2() {
  return new Promise((resolve, reject) => {
    func1()
    .then(obj => {
      return resolve(obj.method('stuff'))
    })
  })
}

Note: They are each in a separate module, with func2 require'ing/importing func1

I'm wondering how I should go about asserting that func2 resolves obj.method() with stuff as the argument. I was thinking about stubbing it using sinonJS, but I'm not sure how to go about stubbing it (As I can't really require/import the obj method to stub in my unit-test file).

My available test-suite is Mocha/Chai/Sinon, however if it's doable in some other way, those aren't a strict requirement.

Upvotes: 0

Views: 2770

Answers (1)

Alex
Alex

Reputation: 5646

Slight workaround, but you should be able to do something like the following.

import * as functions from './func1';

const obj = {
  method: sinon.spy()
};

sinon.stub(functions, 'func1')
  .returns(new Promise(obj));

expect(obj.method).to.have.been.calledWith('stuff'); // sinon-chai expectation

Upvotes: 1

Related Questions