jest-mock-functions
Ever needed to mock all the functions of an object but nothing else?
This package mocks all functions inside a arrays, objects, Maps, Sets and class instances and copys overs everything else into a new object.
Note: This package is specifically meant for use with Jest
Installation
npm install jest-mock-functions
or
yarn add --dev jest-mock-functions
How to use it
Objects
You can mock objects:
;const mockedObject = ;
Arrays
You can mock the contents of arrays:
;// Will return [1, jest.fn(), jest.fn()];const mockedArray = ;
Sets
Class instances
Mocking an instance of class will add mocked functions for all the instance's functions and all of it's prototype's functions.
{ this { return 1; } } { return 2; } const mocked = ;// Has been mockedmocked;// Has been mockedmocked; const notMocked = ;// Returns 1notMocked;// Returns 2notMocked;
Options
You can pass options into mockFunctions
.
E.g. mockFunctions(aValue, { recursive: true })
recursive: boolean | RecursionOptions
You can mock functions inside arrays inside objects. With { recursive: true }
.
;// Will return { test: [ jest.fn(), 1] }const mockedThing = ;
or the other way around
;// Will return [ { test: jest.fn() }, { aInt: 1 }]const mockedThing = ;
go crazy with it
;// Will return [[{ this: { is: [{ rediculous: jest.fn() }]}}]]const mockedThing = ;
Class instances
By default, class instances are not mocked recursively. If you wish to mock class instances add the option: { recursive: { classInstances: true } }
.
onMockedFunction: (mockedFunction, originalValue) => any
Use this if you want to do something with the mocked functions. E.g. Return a specific value:
;const mockedObject =