【问题标题】:Build own assert class建立自己的断言类
【发布时间】:2018-02-04 12:25:15
【问题描述】:

我想创建自己的小断言类。我尝试安装 mocha 和 chai,但在这些模块的深处出现了很多错误,所以目前我宁愿尝试自己构建的东西,如果不是至少学习更多 TypeScript。

我找到了一个很好的类模板 (https://gist.github.com/brunolm/6031927),并且 IsFalse、IsTrue、AreEqual 的实现工作得很好。我用 IsNullOrUndefined 扩展了它以满足我的需要,到目前为止一切都很好。

我也想使用 IsInstanceOf 测试。它是这样实现的:

public static IsInstanceOfType(expectedType: Function, actual: any): void {
    if (!(actual instanceof expectedType)) {
        // some more code to construct a message, and throw
    }
}

但我无法让该代码正常工作。我不知道如何/传递什么作为第一个参数。我试试这样

Assert.IsInstanceOfType((): List<string> => { return undefined; }, list);

List 是我自己的通用集合类,而 list 是它的一个实例(或者不是......这要找出来)。

上面的代码可以编译,但是失败了,即使不应该断言也会失败。我发现“传递一个返回您期望的类型的函数”很奇怪,如果可能的话,我更喜欢更好的东西。 如果这是要走的路,那我用错了——你会怎么用?

我问了作者,他建议我应该这样打电话

Assert.IsInstanceOfType(List<string>, list);

但是编译器并没有通过,这是不对的,不是吗?我无法让它工作 - 那是写出的类型,而不是函数?!?

有什么建议吗?

【问题讨论】:

  • 与原始链接类相比,我按照此处显示的方式切换了函数参数顺序。遗憾的是,这还不是问题的解决方案。如何传递参数的问题,而不是它们的放置顺序......

标签: typescript types tdd assert


【解决方案1】:
public static IsInstanceOfType(type: Function, instance: any): void {
    if (!(instance instanceof type)) {
        // some more code to construct a message, and throw
    }
}

然后

const Foo = function() {};
Assert.IsInstanceOfType(Foo, new Foo()); // true

我希望这将引导您找到解决方案。

如果您需要更多帮助,请将您的 List 对象的代码提供给我们。

【讨论】:

    猜你喜欢
    • 2011-03-19
    • 2010-09-26
    • 2013-12-30
    • 2020-06-30
    • 1970-01-01
    • 2010-12-27
    • 2010-09-15
    • 1970-01-01
    • 2021-07-28
    相关资源
    最近更新 更多