I'm struggling with mocking a method when mocking an ES6 class, using MockedClass of the jest library.
Example:
export default class CalculatorService {
constructor() {
// setup stuff
}
public add(num1: number, num2: number): number {
return num1 + num2;
}
}
The following works as expected:
import CalculatorService from 'services/calculatorService';
jest.mock('services/calculatorService');
const MockedCalculatorService = CalculatorService as jest.MockedClass<typeof CalculatorService>;
describe('Tests', () => {
test('Test flow with Calculator service', () => {
// Arrange
// Act
implementation(1,2); // Where CalculatorService is used
// Assert
const mockServiceInstance = MockedService.mock.instances[0];
expect(mockServiceInstance.add).toHaveBeenCalledWith(1,2);
});
}
But say I wanted to mock add to always return 5, no matter the input.
With jest.Mocked it's done like: MockedService.add.mockReturnValue(5) if I understand it correctly here. But how do I solve it when I've mocked a class?
EDIT: Ismail gave the option to mock the whole implementation in the
jest.mock() invocation. However, in this case, ideally, I'd like to mock the implementation/return value for each test.
implementation? How did you use theCalculatorService?