I've encountered a challenge with mocking a method while mocking an ES6 class using the MockedClass
feature of the jest library.
For instance:
export default class CalculatorService {
constructor() {
// setup stuff
}
public add(num1: number, num2: number): number {
return num1 + num2;
}
}
The current approach is functioning 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);
});
}
However, what if I want to mock the add
method to always return 5 regardless of input?
Using jest.Mocked
, it can be achieved with
MockedService.add.mockReturnValue(5)
based on my understanding mentioned here. But how can I implement this when dealing with a mocked class?
UPDATE: Ismail suggested the option to mock the entire implementation within the jest.mock()
declaration. Nonetheless, in this scenario, I prefer to mock the implementation/return value for each individual test ideally.