I am facing an issue with a class dedicated to handling a data type known as ProductMetadata
. This class interacts with a lookup service that selects a specific handler based on the type of ProductMetadata
received from a LookupService
object. I have been able to mock all objects except for the DataHandler
instance created within the process method.
Below is the code snippet:
import { ProductMetadata } from './product/metadata'
import { LookupService } from './service/lookup'
import { DataHandler } from './product-handlers/data-handler'
class ProductDataHandler {
async process(data: ProductMetadata, service: LookupService): Promise<void> {
if (data.value) {
try {
const processor = await service.getProductHandlerForType(data.type)
const dataHandler = new DataHandler(processor)
await dataHandler.insert(data)
} catch (error) {
console.error('Failed to persist data ', error)
}
}
}
}
export { ProductDataHandler }
The challenging part for me is mocking this line of code: Unfortunately, this instance is internally created and I'm unsure if Jest provides a way to effectively mock it. Everything else in the setup works fine apart from the fact that dataHandler
remains undefined.
const dataHandler = new DataHandler(processor)
How can I successfully mock the DataHandler
class?
I attempted the following approach but encountered a
TypeError: DataHander is not a constructor
:
jest.mock('./product-handlers/data-handler', () => (
{
__esModule: true,
insert: jest.fn()
}
))
``ts
import {ProductProcessor } from './processor/product-processor'
class DataHandler {
private productProcessor:ProductProcessor
constructor(productProcessor: ProductProcessor){
this.productProcessor = productProcessor
}
...
}