jwolsborn
jwolsborn

Reputation: 716

Stub a function of a function with jest

I'm trying to stub a function of a function (well I need to stub both really)

Here is an example

return res.foo(100).bar(aVar)

and here is what my test mocking looks like

let res = {
    foo: ()=> jest.fn( {bar:()=> jest.fn()})
}

However when running my tests I get the error 'TypeError: res.foo(...).bar is not a function'

Upvotes: 3

Views: 2787

Answers (1)

Brian Adams
Brian Adams

Reputation: 45850

You're close.

Just three changes needed:

  • jest.fn() returns a function so it doesn't need to be wrapped in a function
  • jest.fn() takes an optional implementation parameter which should be a function
  • If you want to spy on bar then return the same spy in the mock implementation of foo, otherwise a new bar spy gets created each time foo is called.

So your mock should look like this:

const barSpy = jest.fn();
let res = { foo: jest.fn(() => ({ bar: barSpy })) };

Here is a working demo:

const func = (res, aVar) => {
  return res.foo(100).bar(aVar);
}

test('stub chained functions', () => {
  const barSpy = jest.fn(() => 'the result');
  const res = { foo: jest.fn(() => ({ bar: barSpy })) };

  const result = func(res, 'a var');

  expect(res.foo).toHaveBeenCalledWith(100);  // SUCCESS
  expect(barSpy).toHaveBeenCalledWith('a var');  // SUCCESS
  expect(result).toBe('the result');  // SUCCESS
})

Upvotes: 4

Related Questions