【问题标题】:How to assert data type with Jest如何用 Jest 断言数据类型
【发布时间】:2020-10-15 06:54:48
【问题描述】:

我正在使用 Jest 测试我的 Node 应用程序。

我是否可以期望/断言一个值是日期对象?

expect(typeof result).toEqual(typeof Date())

是我的尝试,但自然返回 [Object]。所以这也将通过{}。

谢谢!

【问题讨论】:

    标签: node.js jestjs


    【解决方案1】:

    对于更新版本的 Jest > 16.0.0

    有一个名为toBeInstanceOf 的新匹配器。您可以使用匹配器来比较值的实例。

    示例:

    expect(result).toBeInstanceOf(Date)
    

    对于版本为 < 16.0.0 的 Jest:

    instanceof证明result变量是否为DateObject。

    示例:

    expect(result instanceof Date).toBe(true)
    

    另一个匹配原始类型的例子:

    booleannumberstring & function

    expect(typeof target).toBe("boolean")
    expect(typeof target).toBe("number")
    expect(typeof target).toBe("string")
    expect(typeof target).toBe('function')
    

    array & object:

    expect(Array.isArray(target)).toBe(true)
    expect(target && typeof target === 'object').toBe(true)
    

    null & undefined:

    expect(target === null).toBe('null')
    expect(target === undefined).toBe('undefined')
    

    Promiseasync function

    expect(!!target && typeof target.then === 'function').toBe(true)
    

    参考资料:

    【讨论】:

    • 我还能检查变量是否是 Date[] 的实例吗?
    • 这不适用于几个标量原语,包括布尔、数字和字符串,如果这些值以通常的方式声明为文字。 5 instanceof Number 是假的,'tom' instanceof String 也是如此。 typeof 非常适合他们。对于更棘手的情况,请使用 lodash 或 is 之类的库
    • @Tom 问题询问Date 对象。当然,在某些情况下你必须使用关键字typeof
    【解决方案2】:

    Jest 支持toBeInstanceOf。请参阅their docs,但这是他们在回答时所拥有的示例:

    class A {}
    
    expect(new A()).toBeInstanceOf(A);
    expect(() => {}).toBeInstanceOf(Function);
    expect(new A()).toBeInstanceOf(Function); // throws
    

    【讨论】:

      【解决方案3】:

      如果您正在处理 JSX,您可以执行以下操作

      expect(result.type).toBe(MyComponent);
      

      示例

      component = shallow(<MyWidget {...prop} />);
      
      instance = component.instance();
      const result = instance.myMethod();
      
      expect(result.type).toBe(MyComponent);
      

      在此示例中,myMethod() 返回MyComponent,我们正在对其进行测试。

      【讨论】:

        猜你喜欢
        • 2019-04-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-23
        • 1970-01-01
        • 1970-01-01
        • 2022-08-09
        • 2014-01-22
        • 1970-01-01
        相关资源
        最近更新 更多