【问题标题】:Jasmine spy on new object?茉莉花窥探新物体?
【发布时间】:2016-08-30 03:07:17
【问题描述】:

我有一个我正在尝试测试的 TypeScript(最终测试实际的 JavaScript)方法。很简单:

private static myMethod(foo: IFoo): void {
    let anInterestingThing = new InterestingThing();
    foo.bar = anInterestingThing.getSomethingCool();
}

我想测试 getSomethingCool 是否已被调用,通常我只会做一个简单的 spyOn 但我不知道如何监视新的 anInterestingThing 对象。最好的方法是什么?

【问题讨论】:

  • 这是不可能的。当您新建对象时,您无法知道引用将是什么。据我所知,这只是不可测试的代码。要么用工厂函数的依赖注入重构它。

标签: javascript typescript jasmine


【解决方案1】:

如果getSomethingCool是一个原型方法,你可以写

jasmine.spyOn(InterestingThing.prototype, "getSomethingCool");

但是,这在实践中会非常脆弱。 InterestingThing 可能会更改为使 getSomethingCool 成为实例成员,或者在其静态构造函数期间捕获对原型函数的引用等。

【讨论】:

    猜你喜欢
    • 2012-04-19
    • 2020-09-09
    • 2014-12-12
    • 1970-01-01
    • 2017-06-11
    • 2015-07-26
    • 1970-01-01
    • 2023-03-23
    • 2014-02-21
    相关资源
    最近更新 更多