【发布时间】:2020-10-15 06:54:48
【问题描述】:
我正在使用 Jest 测试我的 Node 应用程序。
我是否可以期望/断言一个值是日期对象?
expect(typeof result).toEqual(typeof Date())
是我的尝试,但自然返回 [Object]。所以这也将通过{}。
谢谢!
【问题讨论】:
我正在使用 Jest 测试我的 Node 应用程序。
我是否可以期望/断言一个值是日期对象?
expect(typeof result).toEqual(typeof Date())
是我的尝试,但自然返回 [Object]。所以这也将通过{}。
谢谢!
【问题讨论】:
对于更新版本的 Jest > 16.0.0:
有一个名为toBeInstanceOf 的新匹配器。您可以使用匹配器来比较值的实例。
示例:
expect(result).toBeInstanceOf(Date)
对于版本为 < 16.0.0 的 Jest:
用instanceof证明result变量是否为DateObject。
示例:
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)
参考资料:
【讨论】:
5 instanceof Number 是假的,'tom' instanceof String 也是如此。 typeof 非常适合他们。对于更棘手的情况,请使用 lodash 或 is 之类的库
Date 对象。当然,在某些情况下你必须使用关键字typeof。
Jest 支持toBeInstanceOf。请参阅their docs,但这是他们在回答时所拥有的示例:
class A {}
expect(new A()).toBeInstanceOf(A);
expect(() => {}).toBeInstanceOf(Function);
expect(new A()).toBeInstanceOf(Function); // throws
【讨论】:
如果您正在处理 JSX,您可以执行以下操作
expect(result.type).toBe(MyComponent);
示例:
component = shallow(<MyWidget {...prop} />);
instance = component.instance();
const result = instance.myMethod();
expect(result.type).toBe(MyComponent);
在此示例中,myMethod() 返回MyComponent,我们正在对其进行测试。
【讨论】: