简体   繁体   English

无法使用Sinon在类中存根箭头函数

[英]Cannot stub arrow function in a class using Sinon

  • Sinon version : v2.0.0-pre.2 Sinon版本:v2.0.0-pre.2
  • Environment : Windows 10 环境:Windows 10
  • Other libraries you are using: Typescript, babel, mocha, chai 您正在使用的其他库:Typescript,babel,mocha,chai

What did you expect to happen? 您期望发生什么?

I expected to be able to stub an arrow function in a class. 我希望能够在类中添加箭头函数。

What actually happens 实际发生了什么

I can't stub an arrow function, however, I can stub the class prototype function. 我不能存根箭头函数,但是,可以存根类原型函数。

FAILED TESTS:
  ExampleClass tests
    × should stub thisDoesntWork arrow function
      Chrome 52.0.2743 (Windows 10 0.0.0)
    TypeError: Attempted to wrap undefined property thisDoesntWork as function
        at wrapMethod (webpack:///~/sinon/pkg/sinon.js:3138:0 <- test-bundler.js:7377:21)
        at Object.stub (webpack:///~/sinon/pkg/sinon.js:2472:0 <- test-bundler.js:6711:12)
        at Context.<anonymous> (webpack:///src/stores/sinon.test.ts:22:51 <- test-bundler.js:96197:72)

How to reproduce 如何繁殖

export class ExampleClass {
    thisWorks() {
        return 0;
    }

    thisDoesntWork = () => {
        return 0;
    }
}

describe("ExampleClass tests", () => {
    it("should stub thisWorks function", () => {
        let stubFunctionA = sinon.stub(ExampleClass.prototype, "thisWorks");
    });
    it("should stub thisDoesntWork arrow function", () => {
        let stubFunctionB = sinon.stub(ExampleClass, "thisDoesntWork");
    });
});

I've never used sinon , but in their documentation it states for the sinon.stub function that it: 我从未使用过sinon ,但是在他们的文档中它声明了sinon.stub函数:

Replaces object.method with a stub function 用存根函数替换object.method

If you look at the compiled js code of your ExampleClass : 如果您查看ExampleClass的已编译js代码:

var ExampleClass = (function () {
    function ExampleClass() {
        this.thisDoesntWork = function () {
            return 0;
        };
    }
    ExampleClass.prototype.thisWorks = function () {
        return 0;
    };
    return ExampleClass;
}());

Then you'll see that ExampleClass.prototype.thisWorks is defined, but there's no ExampleClass.thisDoesntWork definition, not even ExampleClass.prototype.thisDoesntWork . 然后,您将看到定义了ExampleClass.prototype.thisWorks ,但是没有ExampleClass.thisDoesntWork定义,甚至没有ExampleClass.prototype.thisDoesntWork

The thisDoesntWork method is added only in the constructor (arrow functions aren't really class methods, they are just class members with a function type). thisDoesntWork方法仅添加到构造函数中(箭头函数不是真正的类方法,它们只是具有函数类型的类成员)。

I suspect that this will work: 我怀疑这会起作用:

describe("ExampleClass tests", () => {
    it("should stub thisDoesntWork arrow function", () => {
        let stubFunctionB = sinon.stub(new ExampleClass(), "thisDoesntWork");
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM