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

Cannot stub arrow function in a class using Sinon

你预计会发生什么?

我希望能够在 class 中添加一个箭头函数。

实际发生了什么

我不能对箭头函数进行 stub,但是,我可以对 class 原型函数进行 stub。

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)

如何重现

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");
    });
});

我从未使用过 sinon,但在他们的文档中它声明 sinon.stub 函数:

Replaces object.method with a stub function

如果你查看你的ExampleClass编译后的js代码:

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

然后你会看到 ExampleClass.prototype.thisWorks 被定义了,但是没有 ExampleClass.thisDoesntWork 定义,甚至 ExampleClass.prototype.thisDoesntWork.

也没有

thisDoesntWork 方法仅在构造函数中添加(箭头函数并不是真正的 class 方法,它们只是具有函数类型的 class 成员)。

我怀疑这会起作用:

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