TypeError: Attempted to wrap undefined property as function

不羁的心 提交于 2020-01-03 17:05:49

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/42271151/typeerror-attempted-to-wrap-undefined-property-as-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!