I have class B which is dependent on class A. I want to test a method of class B which is internally calling a method of class A. Now, I want to unit test my method of class B by mocking class A.
My code structure:
class A {
getSomething() {
return "Something";
}
}
class B {
constructor(objectOfClassA: A) {
this._objectOfClassA = objectOfClassA;
}
functionofClassBToTest() {
const returnValueFromClassA = this.__objectOfClassA.getSomething();
return returnValueFromClassA;
}
}
What I have tried so far:
import ....
import { mocked } from 'jest-mock';
jest.mock("./A", () => {
return {
A: jest.fn().mockImplementation(() => {
return {
getSomething: getSomethingMock
}
})
};
});
const getSomethingMock = jest.fn().mockImplementation(() => {
return "Mock value";
});
const mockA = mocked(A, true);
test("test functionofClassBToTest", () => {
const classBToTest = new B(mockA);
expect(classBToTest.functionofClassBToTest.toStrictEqual("Mock value");
});
This is the error that I am getting:
TypeError: this._objectOfClassA.getSomething is not a function
Note: I don’t want to initialize an object of class A inside my test function. I only want to mock the class.
I also found some previous posts on SO : Post1 and Post2 but nothing worked.