Search code examples
javascriptjestjs

How to mock this keyword in Jest test cases


My JS script has something like this:

 window.object_name = {
       //defined function
       testFunction: function(arg1,arg2){
    
       }
   
       testFunction_2 : function(){
      
          //calling testFunction in anotherfunction using 'this' keyword
          this.testFunction();
       }

    }

Calling testFunction in anotherfunction using this keyword but while running test cases this does not have reference of testFunction.

Tried to mock this keyword or redefining does not work.


Solution

  • If you want this in testFunction_2 to refer to object_name, you should call it in any of these ways:

    // direct property access assigns the object left of the . to `this`
    object_name.testFunction_2()
    
    const { testFunction_2 } = object_name
    // without property access, `this` defaults to globalThis (the window object)
    testFunction_2() // fails with 'this.testFunction is not a function'
    
    // call or apply
    testFunction_2.call(object_name)
    testFunction_2.apply(object_name)
    
    // bind `this`
    const testFnBound = testFunction_2.bind(object_name)
    testFnBound()