Search code examples
javascripttypescriptjestjsvitest

Mock constructor to throw exception


I'm trying to write a test in which it should fail when instantiating the S3Client object. From what I can tell, when mocked by Vitest (equivalent to Jest), Vitest replaces the constructor with its own, and mine is never called.

Below is my attempt.

vi.mock('@aws-sdk/client-s3', async () => {
  const module = await vi.importActual<typeof import('@aws-sdk/client-s3')>('@aws-sdk/client-s3')

  Object.defineProperty(module.S3Client.prototype, 'constructor', {
    value: function () {
      throw new Error("Can't construct S3Client")
    },
    writable: true,
    configurable: true,
  })

  return {
    ...module,
  }
})

My question is: How could I throw an exception from the constructor?


Solution

  • Not sure how you can do it with vitest, but with jest you can probably do something like

    jest.mock('@aws-sdk/client-s3', () => {
      return {
        S3Client: jest.fn().mockImplementation(() => {
          throw new Error('constructor error');
        }),
      };
    });
    
    describe('Test new S3Client exception', () => {
      test('Create new S3Client instance should throw an error', () => {
        expect(() => {
          new SQSClient({});
        }).toThrow(new Error('constructor error'));
      });
    });