Steffany
Steffany

Reputation: 156

Sinon stub not replacing function in test

I've looked through similar questions and still cannot figure out why my sinon stub isn't working. The test is still calling the original function.

userFlow.js

function authorization() {
  const options = {
    name: 'buzz',
    state: 'bazz'
  }

  return options
}

const credentials = authorization()

async function main() {
  return credentials.name;
}


main();

module.exports = {
  authorization,
  main
};

test.userFlow.js

const userFlow = require('../userFlow.js');

describe('userFlow()', function() {
    it('should authorize', async function() {
        options = {
            name: 'foo',
            state: 'bar',
        }; 
        sinon.stub(userFlow, 'authorization').returns(options);
        const output = userFlow.main()
        assert(output === foo)
    })
})

I end up with output === buzz. Thanks for help.

Upvotes: 1

Views: 286

Answers (1)

Jackie
Jackie

Reputation: 23477

I think the problem here is order of operations. When you do this...

const userFlow = require('../userFlow.js');

It runs this...

const credentials = authorization()

So your sinon override doesn't matter. What I would try is something like this...

async function main(authorization) {
  return authorization().name;
}
...
const output = userFlow.main(userFlow.authorization)

Upvotes: 4

Related Questions