TypeError: Attempting to wrap an undefined property as a function

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 this as follows:

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 versions 1 and 2 of the sinon library.

+4
source share
1 answer

Its a problem with how you defined your method myMethod. When you use getto define a method, it is actually treated as a property, not a method. This means that you can access cls.myMethod, but cls.myMethod()will throw an error, since it is not a function

Problem

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

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

, myMethod ,

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

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

sinon.stub

+2

Source: https://habr.com/ru/post/1669914/


All Articles