I have been searching for a comprehensive example that demonstrates how to properly mock all three elements (ClassA constructor, ClassA.func1 instance function, and ClassA.func2 static function) in my TypeScript project. In the code under test, I need to verify the mocked constructor, function, and static function using Jest for unit testing purposes.
While I typically use the mock factory approach for mocking Classes, I am facing difficulties in implementing it in this scenario. Below is an outline of the structure:
// ClassA.ts
export class ClassA {
constructor() {
// construction logic
}
public async func1(x: int): Promise<void> {
// func1 logic
}
static func2(x: string | number): x is string {
// func2 logic
let conditionIsMet: boolean;
// conditionIsMet logic
if (conditionIsMet) {
return true;
}
return false;
}
}
// CodeUnderTest.ts
import { ClassA } from './ClassA';
export class ClassB {
public async foo() {
if (ClassA.func2('asdf')) {
const a = new ClassA();
await a.func1(45);
}
}
}
// UnitTest.ts
import { ClassB } from './ClassB';
// mock factory
const mockFunc1 = jest.fn();
const mockStaticFunc2 = jest.fn();
jest.mock('./ClassA', () => ({
ClassA: jest.fn().mockImplementation(() => ({
func1: mockFunc1,
func2: mockStaticFunc2,
}),
});
beforeAll(() => {
mockStaticFunc2.mockReturnValue(true);
});
describe('when ClassB.foo() is called', () => {
describe('when ClassA.func2 is given a string parameter', () => {
it('then ClassA.func2 is invoked with expected parameters, ClassA is constructed, ClassA.func1 is invoked with expected parameters', () => {
// arrange
const clsB = new ClassB();
// execute
clsB.foo();
// expect
expect(mockStaticFunc2).toHaveBeenCalledTimes(1);
expect(mockStaticFunc2).toHaveBeenNthCalledWith(1, 'asdf');
expect(ClassA).toHaveBeenCalledTimes(1);
expect(mockFunc1).toHaveBeenCalledTimes(1);
expect(mockFunc1).toHaveBeenNthCalledWith(1, 45);
});
});
});
Could someone provide a detailed solution or example that outlines how to effectively mock all aspects (ClassA constructor, ClassA.func1 instance function, and ClassA.func2 static function) as described?