I have a specific Class that I want to test using the mocha-chai testing framework in TypeScript. My approach involves incorporating ts-mockito for mocking purposes.
export class MainClass implements IMainClass {
private mainResource: IMainResource;
constructor() {
this.mainResource = new MainResource();
}
public async doSomething(input) {
const data = this.mainResource.getData(input);
//logic implementation
}
}
The MainResource class structure is similar to this:
export class DataService implements IDataService {
private dataItems: Map<string, DataItem>;
constructor(){
this.dataItems= new Map();
}
public async retrieveData(): Promise<DataItem> {
//add data items to the map
}
public async getData(dataId): Promise<DataItem>{
//retrieve specified data item from the map
}
}
During my testing phase, I attempted to mock the getData method of MainResource like so:
const mainResource: IMainResource = new MainResource ();
const mainResourceSpy = spy(mainResource);
when(mainResourceSpy.getData(anyString())).thenResolve(someData);
Then, I executed the doSomething method of MainClass in the following manner:
mainClass.doSomething(input)
My expectation was for the getData call within the doSomething method to be mocked and return a specific data object.
Unfortunately, the test results did not align with my expectations. The mock was not utilized, and instead, the getData() function proceeded with its actual implementation, returning undefined.
After researching online, it appears that this issue may be due to the constructor initializations in the MainResource class.
I attempted removing the constructor, which resulted in successful mocking of the getData method.
However, I require the constructor to instantiate the map object and manage the data items effectively.
Is there a workaround that would allow me to mock getData() while retaining the constructor functionality?
Could it be possible that I am making an error somewhere in my code?
I acknowledge that I am relatively new to TypeScript and ts-mockito, thus any guidance would be immensely valued.