我正在使用 Jest 来测试我的 Node 应用程序。
我是否可以期望/断言一个值是一个日期对象?
expect(typeof result).toEqual(typeof Date())
是我的尝试,但自然返回[Object]。所以这也会通过 {}。
谢谢!
Lao*_*tih 31
对于更新版本的 Jest > 16.0.0:
有一个新的匹配器叫做toBeInstanceOf. 您可以使用匹配器来比较值的实例。
例子:
expect(result).toBeInstanceOf(Date)
Run Code Online (Sandbox Code Playgroud)
对于 Jest 版本< 16.0.0:
使用instanceof证明是否result变量是Date对象或没有。
例子:
expect(result instanceof Date).toBe(true)
Run Code Online (Sandbox Code Playgroud)
匹配原始类型的另一个示例:
boolean, number, string& function:
expect(typeof target).toBe("boolean")
expect(typeof target).toBe("number")
expect(typeof target).toBe("string")
expect(typeof target).toBe('function')
Run Code Online (Sandbox Code Playgroud)
array& object:
expect(Array.isArray(target)).toBe(true)
expect(target && typeof target === 'object').toBe(true)
Run Code Online (Sandbox Code Playgroud)
null& undefined:
expect(target === null).toBe('null')
expect(target === undefined).toBe('undefined')
Run Code Online (Sandbox Code Playgroud)
Promise或async function:
expect(!!target && typeof target.then === 'function').toBe(true)
Run Code Online (Sandbox Code Playgroud)
参考:
接受的答案有效,但容易出现拼写错误。特别是对于原始类型
// This won't work. Misspelled 'string'
expect(typeof target).toBe("strng")
Run Code Online (Sandbox Code Playgroud)
我在文档中偶然发现的一个更好的方法(没有明确定义为测试类型的方法)是:
expect(id).toEqual(expect.any(Number))
expect(title).toEqual(expect.any(String))
expect(feature).toEqual(expect.any(Boolean))
expect(date).toEqual(expect.any(Date))
Run Code Online (Sandbox Code Playgroud)
玩笑支持toBeInstanceOf. 查看他们的文档,但这是他们在回答时的示例:
class A {}
expect(new A()).toBeInstanceOf(A);
expect(() => {}).toBeInstanceOf(Function);
expect(new A()).toBeInstanceOf(Function); // throws
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14708 次 |
| 最近记录: |