Home > Enterprise >  Mock partial class AdmZip using jest
Mock partial class AdmZip using jest

Time:07-02

tried all the examples and none seems to work, the most promising one is the one below, but it actually also isn't working. What I'm hoping to achieve is to use all regular AdmZip functions except the writeZip and updateFile, those should be mocked and will be checked using their spy.

But currently I get the error that admZip.getEntries() is not a function, so the actual part of my mock seems to be wrong, any hints how I get the actual getEntries-method inside my mock?

jest.mock('adm-zip', () => {
  const actual = jest.requireActual('adm-zip');
  return function(): AdmZip {
      return {
        ...actual, // <--- was hoping this will integrate the other original methods like getEntries()
        writeZip: jest.fn(),
        updateFile: jest.fn()
      }
  }
});

and another approach:

jest.mock('adm-zip', () => {
  const actual = jest.requireActual('adm-zip');
  return jest.fn().mockImplementation(() => ({
    ...actual,
    writeZip: jest.fn(),
    updateFile: jest.fn()
  }))
});

and totally random

jest.mock('adm-zip', () => {
  const actual = jest.requireActual('adm-zip');
  return {
    __esModule: true,
    ...actual,
    AdmZip: jest.fn().mockImplementation(() => {
      return {
        ...jest.requireActual('adm-zip'),
        writeZip: jest.fn(),
        updateFile: jest.fn()
      }
    })
  }
});

CodePudding user response:

Not sure what the pure jest version would be, but I achieved my "Partial Mock" with another package: MockProxy from jest-mock-extended

First import:

import { mock, MockProxy } from 'jest-mock-extended';

Then only define the methods you want to actually do something:

const admZip: MockProxy<AdmZip> = mock<AdmZip>({
  getEntries: new AdmZip(path.join('./apps/backend/test/data/unittest/sample-ibans.zip')).getEntries,
});

Then we use the MockProxy as a return for our actual zip-reading-method:

jest.spyOn(FileHandler, 'createAdmZip').mockResolvedValue(admZip);

Now we can test all zip-functionality by reading an actual zip, but all write and update functions are still mock, so the zip will not be changed, but the code still runs through as if.

Now all methods are mocked, except the getEntries, since AdmZip is a class, we had to hardcode our zip-file-path, but you can re-create the mock with a method and change the path anytime. So that was my "workaround"

  • Related