How to write a unit test to check JSZIP.loadAsync function rejects

Issue

This Content is from Stack Overflow. Question asked by Swarup Chavan

Request to please help to write a unit test case to check the negative scenario of jszip.loadasync

the function that I use it within is as follows

public processArtifact(artfact:Artfact): Promise<Artfact> {
        
        const file_path = path.resolve(artfact.getfile_path());
        return new Promise(async(resolve,reject) => {
            fs.promises.readFile(file_path)
                .then(async function(data) {
                    await JSZip.loadAsync(data).then(async function (zip:any) {
                        //some logic
                        resolve(1);
                    })
                    .catch(function(error) {
                        LoggerWrapper.error(`Error while extracting ZIP of ${artfact.getname()}`, error)
                        reject(error);
                    });                    
                })
                .catch(function(error) {
                    LoggerWrapper.error(`Error while fetching ZIP of ${artfact.getname()}`, error)
                    reject(error);
                });
        })
    }

I need to check the .catch part of both fs.promises.readFile and JSZIP.loadAsync in the unit test case

I tried to write the unit test as follows but no luck

jest.mock(‘JSZip’); //have mocked JSZIP

 test('test path is rejected readfile', async () => {
        const mockGetRestClient = jest.fn();
        JSZip.loadAsync = mockGetRestClient;
        mockGetRestClient.mockRejectedValueOnce(new InternalServerException());   
        try {
          artfactService.processArtfact(artfact);
        
          expect(JSZip.loadAsync).rejects.toThrowError();
        }
        catch (e: any) {
          const a  = e;
         }
      });

Can anyone please guide as to how I can write,need help



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?