saber1897
saber1897

Reputation: 1

How to use sinon to mock a function within a function?

yellow.js

async function yellow(
  prop1,
  prop2
) {
  //does stuff and returns an array
  return [1, 2, 3]
}

blue.js

const Yellow = require('./yellow')

async function blue(
  prop1,
  prop2
) {
 
      const getIds = await Yellow(
        prop1,
        prop2
      )

      //Do stuff and return an array


  return [1, 2, 3]
}

blue.test.js

it('should return an array of ids', async () => {
      await blue(
        1,
        2
      )
    })

How do I stub yellow when I try to unit test blue using sinon?

I am aware of being able to stub the property of an object like sinon.stub(Yellow, 'yellow') but in this case it is throwing an error

Upvotes: 0

Views: 219

Answers (2)

Chalom.E
Chalom.E

Reputation: 697

No need to use sinon. You can use the native mock function with jest. https://jestjs.io/docs/mock-functions

Upvotes: 0

jumpingRock
jumpingRock

Reputation: 46

Its not clear if you instructed stub to resolve an async call of yellow in your question but it should work if you follow the below.

const Yellow = require('Yellow');

const Sinon = require('Sinon');

const yellowStub = Sinon.stub(Yellow, 'yellow');

it('should return an array of ids', async () => {
      yellowStub.resolves([1,2,3]);

      await blue(1,2)
    })

Second: you need to call the function yellow after importing Yellow in your blue.js.

    const Yellow = require('./yellow')

    async function blue(prop1, prop2) {
      const getIds = await Yellow.yellow(prop1, prop2)

      //Do stuff and return an array

      return getIds
    }

Third: you need to export yellow function

async function yellow(prop1, prop2 ) {
  //does stuff and returns an array
  return [1, 2, 3]
}

module.exports = { yellow }

Upvotes: 1

Related Questions