javascript - 无法使用 Sinon 在类中 stub 箭头函数

标签 javascript typescript sinon

  • 赛农版本:v2.0.0-pre.2
  • 环境:Windows 10
  • 您正在使用的其他库:Typescript、babel、mocha、chai

您预计会发生什么?

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

实际发生了什么

我不能 stub 箭头函数,但是,我可以 stub 类原型(prototype)函数。

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

我怀疑这会起作用:

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

关于javascript - 无法使用 Sinon 在类中 stub 箭头函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39301935/

相关文章:

javascript - 为什么在 React 单元测试中模拟事件时未定义,使用 sinon.spy 模拟函数和 enzyme.shallow 渲染 React Component?

JavaScript 写一个带有过期时间的 cookie

angular - 在 Angular 2 中更改 url 而不重定向

javascript - 在 VScode 编辑器中显示 Javascript 的 Intellisense 错误

javascript - 匹配Sinon FakeXMLHttpRequest

javascript - 有没有办法使用 sinon 测试下面的代码

javascript - 定义 document.ready() 函数的顺序?

javascript - Jquery:为什么 .val() 在将内部设置为参数时不更改输出?

javascript - 选择一个表单的所有子元素的方法是什么?

AngularFire 更新 -> 哪里