In Jest testing framework , there is a jest.genMockFn()
function that create object which can be called as function and simultaneously accessing it's properties.
var mockFn = jest.genMockFn()
mockFn('Hello world!')
mockFn('The world is yours.')
console.log(mockFn.mock.calls) // [["Hello world!"], ["The world is yours."]]
When I dump mockFn
i get:
{ [Function]
_isMockFunction: true,
mock:
{ calls: [ [Object], [Object] ],
instances: [ [Object], [Object] ] },
mockClear: [Function],
mockReturnValueOnce: [Function],
mockReturnValue: [Function],
mockImpl: [Function],
mockImplementation: [Function],
mockReturnThis: [Function],
_getMockImplementation: [Function] }
I can't figure out how they achieve this. Any ideas? Can you provide code with similar functionality? Thank you.
The definition of a function is
member of the Object type that is an instance of the standard built-in
Function
constructor and that may be invoked as a subroutine
So having an object which can be called is not weird. All functions behave like that.
Specifically, this is done using [[Call]], an internal property only defined for some objects.
Executes code associated with the object. Invoked via a function call expression. [...] Objects that implement this internal method are callable .
This code may allow you to define a function with attributes
var func = function () { };
func.attr = "value";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.