如何使用 Jest 断言数据类型

Jac*_*k.c 12 node.js jestjs

我正在使用 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)

Promiseasync function

expect(!!target && typeof target.then === 'function').toBe(true)
Run Code Online (Sandbox Code Playgroud)

参考:

  • 如果这些值以通常的方式声明为文字,则这对于几个标量基元(包括布尔值、数字和字符串)不起作用。`5 instanceof Number` 为 false,`'tom' instanceof String` 也是如此。`typeof` 对他们来说非常有用。对于更棘手的情况,请使用像 lodash 或 [`is`](https://github.com/sindresorhus/is) 这样的库 (3认同)

Maz*_*awy 7

接受的答案有效,但容易出现拼写错误。特别是对于原始类型

// 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)


Pla*_*ble 6

玩笑支持toBeInstanceOf. 查看他们的文档,但这是他们在回答时的示例:

class A {}

expect(new A()).toBeInstanceOf(A);
expect(() => {}).toBeInstanceOf(Function);
expect(new A()).toBeInstanceOf(Function); // throws
Run Code Online (Sandbox Code Playgroud)