0

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.

1
  • 2
    A function is an object, and therefore you can set/get properties on it like any other JavaScript object. Commented May 3, 2015 at 17:04

2 Answers 2

2

The definition of a function is

4.3.24 function

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. Can you provide an example, please?
@user2078693 function f(){ alert('I am callable'); } f.prop='I can have properties'; f instanceof Object === true
1

This code may allow you to define a function with attributes

var func = function () { };
func.attr = "value";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.