foobar
foobar

Reputation: 4019

Jest.js Mocking a method within a module

I'm testing a generator function with Jest.js but my question is generally about mocking functions within modules.

Foo.js has:-

const Foo = {
   callMe() { 
     return true;
   },
   callMe2() {
     return true;
   }
};
export default Foo;

In my Jest test I want Foo.callMe to throw an error but I can't get it to work with Jest mock.

import Foo from '../Foo';

it('fails my generator function', () => {
  const gen = myGenFunction();
  expect(gen.next().value).toEqual(call(Foo.callMe));
});

The generator function looks something like this:

export function* myGenFunction(action) { 
  try {
    const response = yield call(Foo.callMe);
    console.log('Success');
  } catch(err) {
    console.log('Error!!!');
  } finally {
    // do something else
  }
}

How can I make Foo.callMe throw an error? I've tried a few things, but nothing worked so far.

Upvotes: 1

Views: 622

Answers (1)

foobar
foobar

Reputation: 4019

I have managed to achieve what I wanted by using redux-saga's throw method.

it('fails my generator function', () => {
  const error = { message: 'Look see here, an error' };

  const gen = myGenFunction();
  ...

  expect(gen.throw(error).value).toEqual(
      put(actions.setIsLoading(false)), // action that happens on fail
      'gen should yield an Effect put(actions.setIsLoading(false))'
  );
});

It's nicely documented here: https://redux-saga.js.org/docs/basics/ErrorHandling.html

Upvotes: 1

Related Questions