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');
});
import * as defaultFn from 'module';
it('should ', () => {
jest
.spyOn(defaultFn, 'default')
.mockImplementationOnce(async () => 'value');
});
// __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);
});
});
});
it('should ', () => {
await expect(
asyncFunction(arg)
).rejects.toThrow(ExpectedError);
});
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));
});
Reources:
https://codeburst.io/module-mocking-in-jest-ff174397e5ff
https://github.com/thawkin3/jest-module-mocking-demo