I'm new to jest and trying to write a unit test case which checks if the inner function throws an exception and need to write the unit test case to check it, my outer function looks as below
public async getfacts(): Promise<any> {
let facts: fact[] = [];
return new Promise(async(resolve,reject) => {
try{
let files = await fspromise.readdir(`${envConfig.facts_path}`);
for(const filename of files){
if(path.extname(filename).toLowerCase() == '.zip'){
let file_path = path.join(`${envConfig.facts_path}`,filename);
let artfact = new ArtFact(filename,file_path);
artfact = await this.processArtfact(artifact);
facts.push(artifact);
}
};
resolve(facts);
}
catch(error){
LoggerWrapper.error(`Error while accessing ZIP facts from the source path`, error);
throw error;
}
});
}
the inner function is as below
public processArtfact(artfact:Artfact): Promise<Artfact> {
const file_path = path.resolve(artfact.getfile_path());
let an_meta: any[] = [];
let line_meta: any[] = [];
return new Promise(async(resolve,reject) => {
fs.promises.readFile(file_path)
.then(async function(data) {
await JSZip.loadAsync(data).then(async function (zip:any) {
//somelogic here
resolve(artfact);
})
.catch(function(error) {
LoggerWrapper.error(`Error while extracting ZIP of ${artfact.getname()}`, error)
throw error;
});
})
.catch(function(error) {
LoggerWrapper.error(`Error while fetching ZIP of ${artfact.getname()}`, error)
throw error;
});
})
}
the unit test that I have written to check for the negative scenario is as followed
test('test get artfacts with exception', async () => {
const mockGetRestClient = jest.fn();
artfactService.processArtfact = mockGetRestClient;
mockGetRestClient.mockRejectedValue(new InternalServerException);
try {
const response = await artfactService.getArtfacts();
expect(artfactService.processArtfact).toHaveBeenCalled();
expect(response).toEqual(new InternalServerException);
}
catch (e) { }
});
but whenever i run the unit test case the scenario is not executed it gives and error as
thrown: "Exceeded timeout of 5000 ms for a test.
Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
211 |
212 |
> 213 | test('test get artfacts with exception', async () => {
| ^
214 | const mockGetRestClient = jest.fn();
215 | artifactService.processArtfact = mockGetRestClient;
216 | mockGetRestClient.mockRejectedValue(new InternalServerException);
I tried by setting the setTimeout as well but still the same issue ,what would be the right approach for testing the above scenario any better way to write the test case ?
I did some debugging the error is thrown from the second catch in the inner function but the test case response shows undefined and doesnt even go into catch of the jest test case where i'm going wrong?