Reputation: 716
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
Reputation: 45850
You're close.
Just three changes needed:
jest.fn()
returns a function so it doesn't need to be wrapped in a functionjest.fn()
takes an optional implementation parameter which should be a functionbar
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