我正在使用 Jest 来测试我的 Node 应用程序。
我是否可以期望/断言一个值是日期对象?expect(typeof result).toEqual(typeof Date())
是我的尝试,但自然返回[Object]。所以这也会通过 {}。
谢谢!
最佳答案
用于更新版本的 Jest > 16.0.0
:
有一个名为 toBeInstanceOf
的新匹配器.您可以使用匹配器来比较值的实例。
示例:
expect(result).toBeInstanceOf(Date)
用于 Jest 版本
< 16.0.0
:使用
instanceof
证明是否result
变量是 Date
对象与否。示例:
expect(result instanceof Date).toBe(true)
匹配原始类型的另一个示例:
boolean
, number
, string
& 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')
Promise
或 async function
:expect(!!target && typeof target.then === 'function').toBe(true)
引用:
关于node.js - 如何使用 Jest 断言数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62564800/