0

I want to mock/stub the resolve of a class method that returns a promise when testing another method of the same class. I'm using jest.

I have the following class Blah of which I want to test the foo() method:

export default class Blah {
  foo () {
    this.bar().then(result => {
      // some logic here
    })
  }

  bar () {
    return new Promise(function (resolve, reject) {
      // fetches some stuff over the network
      resolve('hello world')
    })
  }
}

Because foo() uses bar() - a promise returning method that does stuff over the network - I would like to mock the resolve of bar(); let's say make it resolve what up.

Let's say the test would look something like this:

import Blah from './blah'

test('foo() - bar() resolves "what up"', () => {
  const blah = new Blah()
  // mock blah.bar() so that is resolves "what up"

  // {some assertions on blah.foo() here}
})

It's my first time working with jest and I've read through the docs, but I'm still having a hard time wrapping my head around this case.

How can I mock the resolved value of bar() while testing foo()?

0

1 Answer 1

1

Still just JavaScript meaning any object property can be dynamically overwritten:

// in the test file
const blah = new Blah();
blah.bar = _ => Promise.resolve("what up");

// now some assertions about blah.foo
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, if you'll pardon my ignorance, why the _ in this context?
@Juicy it's a fairly common convention for "I don't care what arguments are passed to this function". The underscore (and dollar sign) are valid JavaScript identifiers. I could have written blah.bar = dontcare => Promise.resolve... just force of habit :)

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.