I am currently testing a class called ToTest.ts, which creates an instance of another class named Irrelevant.ts and calls a method on it called doSomething.
// ToTest.ts
const irrelevant = new Irrelevant();
export default class ToTest {
// ... some implementation, constructor, etc.
public static callIrrelevant() {
return irrelevant.doSomething();
}
}
//Irrelevant.ts
export default class Irrelevant {
// ... some implementation, constructor, etc.
public doSomething() {
console.log("doing something");
}
}
How can I successfully mock the irrelevant.doSomething()
function in my jest test?
I have attempted:
import Irrelevant from '../some/path/irrelevant';
test('irrelevant.doSomething is mocked' => {
Irrelevant.prototype.doSomething = () => jest.fn().mockImplementation(() => {
console.log(`function got called`)
});
const toTest = new ToTest();
toTest.callIrrelevant();
});
test('irrelevant.doSomething is mocked -- second try' => {
jest.mock('../some/path/irrelevant')
const mockDoSomething = jest.spyOn(Irrelevant, "doSomething"); // Throws error: Argument of type '"doSomething"' is not assignable to parameter of type 'never'.
mockDoSomething.mockImplementation(() => {
console.log(`function got called`)
});
const toTest = new ToTest();
toTest.callIrrelevant();
});
});
The mock implementations fail to execute in both tests. What is the correct way to mock this situation?