0

I am trying to understand how to mock a function call inside a module when function returns an object, say I have a file

Sample.ts

export function food(){
  return new Fruit();
}
export function taste(){
  return food().getTaste();
}

Now let's say I am trying to test a scenario wether taste() throws an error when getTaste() throws an error.

I understand I can take advantage of "ES6 module cyclic dependency" to import the module into itself as:

import * as sample from './sample';

export function food(){
  return new Fruit();
}
export function taste(){
  return sample.food().getTaste();
}

But I am not sure while testing how do I return mocked Fruit mockedReturnValue does not allow a "Argument of type 'typeof jest'"

const mockedFruit = jest.mock("./fruit", () => ({
    getTaste: jest.fn().mockImplementation(() => {
         throw new Error("Test Error");
    }),
    promise: jest.fn()
}));

test('taste', () => {
  const sample = require('./sample');
  jest.spyOn(sample, 'food').mockReturnValue(mockedFruit);
  expect(sample.taste()).toThrowError();
})
Manfre
  • 656
  • 5
  • 12
  • 30
nfornicole
  • 47
  • 5
  • You don't. That's an implementation detail, treat the module boundary as the interface and test its _behaviour_. – jonrsharpe Oct 28 '21 at 07:17
  • You still want cohesive components and should be testing through the public API, whatever level you're testing at. It's the same reason you don't test private methods. See e.g. https://stackoverflow.com/a/66752334/3001761 for examples of the issues you get when you test too much at the implementation level - it _prevents_ you from refactoring to improve your code. – jonrsharpe Oct 28 '21 at 10:19

0 Answers0