Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Attempted to wrap undefined property as 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 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.

like image 390
jstice4all Avatar asked Feb 16 '17 10:02

jstice4all


1 Answers

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

like image 100
Aditya Singh Avatar answered Sep 17 '22 13:09

Aditya Singh