Skip to content

Instantly share code, notes, and snippets.

@IslamWahid
Last active February 6, 2023 00:32
Show Gist options
  • Save IslamWahid/1abbec621bd71040946faad4d68ce52b to your computer and use it in GitHub Desktop.
Save IslamWahid/1abbec621bd71040946faad4d68ce52b to your computer and use it in GitHub Desktop.
jest advanced cheat sheet

Jest Advanced Cheat Sheet

mock specific ES6 class function

Use jest.spyOn to mock a class function for only a specific test case without affecting the other cases

import ExampleClass from 'ExampleClass';

it('should ', () => {
  jest
      .spyOn(ExampleClass.prototype, 'functionToMock')
      .mockImplementationOnce(async () => 'mockedValue');
});

mock default export function using spyOn

import * as defaultFn from 'module';

it('should ', () => {
  jest
      .spyOn(defaultFn, 'default')
      .mockImplementationOnce(async () => 'value');    
});

mock node_module for example aws-sdk s3

// __mocks__/aws-sdk/clients/s3.ts

export const mockHeadObject = jest.fn();
export const mockListObject = jest.fn();
export const mockUploadFunction = jest
  .fn()
  .mockImplementation(() => ({ promise: async () => ({}) }));

export default jest.fn().mockImplementation(() => {
  return {
    getSignedUrlPromise: () => "signedUrl",
    upload: mockUploadFunction,
    headObject: () => ({
      promise: mockHeadObject,
    }),
    deleteObject: () => ({ promise: async () => ({}) }),
    listObjectsV2: () => ({ promise: mockListObject }),
  };
});
// operations.ts

import {
  doesFileExist,
  getDownloadSignedUrl,
} from './operations';
import { mockHeadObject } from './__mocks__/aws-sdk/clients/s3';

describe('s3 operations', () => {
  describe('getDownloadSignedUrl', () => {
    it('should get signed url by file key', async () => {
      expect(getDownloadSignedUrl('key')).toEqual('signedUrl');
    });
  });

  describe('doesFileExist', () => {
    it('should return boolean to indicate if the file exists or not', async () => {
      mockHeadObject.mockRejectedValueOnce({ code: 'NotFound' });
      await expect(doesFileExist('key')).resolves.toEqual(false);

      mockHeadObject.mockResolvedValueOnce({
        Metadata: { name: 'fileName' },
        LastModified: new Date('01.09.2020'),
      });
      await expect(doesFileExist('key')).resolves.toEqual(true);
    });
  });
});

expect async function to throw

it('should ', () => {
  await expect(
          asyncFunction(arg)
        ).rejects.toThrow(ExpectedError);
});

array matching

it('should ', () => {
  const inputList = Array.from(Array(5), () => ({ foo: 1, bar: 'bar' }));

  const expectedArray = [];
  inputList.forEach(input => {
    expectedArray.push(expect.objectContaining(input));
  });

  const res = doSomeLogic(inputList);
  expect(res).toEqual(expect.arrayContaining(expectedArray));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment