TypeError: Attempted to wrap undefined property as function

jstice4all picture jstice4all · Feb 16, 2017 · Viewed 13.5k times · Source

The example below is simplified. I have a getter method:

class MyClass {
  constructor() {}
  get myMethod() {
    return true;
  }
}

which is processed by babel. And I want to mock it like this:

var sinon = require('sinon');
var MyClass = require('./MyClass');
var cls = new MyClass();

var stub = sinon.stub(cls, 'myMethod');
stub.returns(function() {
  return false;
});

But I get the following error: TypeError: Attempted to wrap undefined property myMethod as function

And this happens on both version 1 and 2 of sinon library.

Answer

Aditya Singh picture Aditya Singh · Feb 16, 2017

Its an issue with how you defined your method myMethod. When you use get to define a method, it actually is treated like a property and not a method. This means you can access cls.myMethod but cls.myMethod() will throw an error as it is not a function

Problem

class MyClass {
  constructor() {}
  get myMethod() {
    return true;
  }
}

var cls = new MyClass();
console.log(cls.myMethod())

Solution You have to update your class definition to treat myMethod as a function like below

class MyClass {
  constructor() {}
  myMethod() {
    return true;
  }
}

var cls = new MyClass();
console.log(cls.myMethod())

With this change now your sinon.stub should work fine