【问题标题】:Cannot stub arrow function in a class using Sinon无法在使用 Sinon 的类中存根箭头函数
【发布时间】:2016-09-02 23:44:08
【问题描述】:
  • 诗乃版本:v2.0.0-pre.2
  • 环境:Windows 10
  • 您正在使用的其他库:Typescript、babel、mocha、chai

您预计会发生什么?

我希望能够在类中存根箭头函数。

实际发生的情况

我不能存根箭头函数,但是,我可以存根类原型函数。

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

【问题讨论】:

    标签: javascript typescript sinon


    【解决方案1】:

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

    用存根函数替换 object.method

    如果你看一下你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 方法仅添加在构造函数中(箭头函数并不是真正的类方法,它们只是具有函数类型的类成员)。

    我怀疑这会起作用:

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

    【讨论】:

    • 谢谢!添加 new ExampleClass() 正确存根“thisDoesntWork”。
    • 你是怎么得到这个编译好的例子的?我在网上使用 babel,但是编译出来的 javascript 完全不同。
    • @roll 三年过去了,我怀疑现在一切都不同了......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 2017-05-14
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多