0

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

2
  • There are so many same questions. See stackoverflow.com/questions/35753797/… Commented Feb 6, 2023 at 3:13
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. Commented Feb 6, 2023 at 7:26

2 Answers 2

1

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 }
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.