Suppose there is a class called Person
which creates an instance of another class named Logger
. How can we ensure that the method of Logger
is being called when an instance of Person
is created, as shown in the example below?
// Logger.ts
export default class Logger {
constructor() {}
log(m: String) {
console.log(m);
// Other operations that are outside testing (e.g., file write).
throw Error('error');
}
}
// Person.ts
import Logger from "./Logger";
export default class Person {
constructor() {
const logger = new Logger();
logger.log('created');
}
// ...
}
// Person.test.ts
import Person from "./Person";
import Logger from "./Logger";
describe('Person', () => {
it('calls Logger.log() on instantiation', () => {
const mockLogger = new Logger();
getCommitLinesMock = jest
.spyOn(mockLogger, 'log')
.mockImplementation(() => {});
new Person(); // Should call Logger.log() on instantiation.
expect(getCommitLinesMock).toBeCalled();
});
});
An alternative approach is to include Logger
as a parameter in the constructor like so:
class Person {
constructor(logger: Logger) {
logger.log('created');
}
// ...
}
However, are there any other methods besides modifying the constructor function to pass this test successfully?