gpt4 book ai didi

node.js - Jest 的 expect(value).toBeInstanceOf(Class) 因 expect(util.promisify(...)()).toBeInstanceOf(Promise) 等而失败

转载 作者:行者123 更新时间:2023-12-03 12:17:01 25 4
gpt4 key购买 nike

设置:

  • Jest : 21.2.1
  • Node :10.16.3
  • npm:6.9.0

为什么 Jest 的 expect 不能将 node.js 的 util.promisify 返回的 promise 识别为 Promise 的实例?

以下失败:

const util = require('util');

const fn = util.promisify((opts, cb) => cb(null, {}));
const promise = fn();
expect(promise).toBeInstanceOf(Promise)

同样,以下失败:

const util = require('util');

const fn = util.promisify((opts, cb) => cb(null, {}));
const promise = fn();
expect(promise.then).toBeInstanceOf(Function);

可以通过检查 typeof promise.then 是否为“函数”来规避此问题,但我对这种行为的原因很感兴趣。

非常感谢您的信息!

最佳答案

Jest 中有一个长期存在的错误,标题为 "Jest globals differ from Node globals" .这严重限制了 toBeInstanceOf 方法的有效性,除非您正在针对您自己的类之一的实例进行测试。目前,最简单的解决方法是简单地测试 expect(fn().constructor.name).toBe('Promise'),充分理解它的用处比 instanceof 要有限得多。总比没有好,因为看起来 Jest 错误不会在不久的将来得到修复。

我也可能建议您的示例测试是不必要的,因为您有点测试 util.promisify 的内部结构,但我知道这可能只是一个更大问题的 MVP。祝你好运!

关于node.js - Jest 的 expect(value).toBeInstanceOf(Class) 因 expect(util.promisify(...)()).toBeInstanceOf(Promise) 等而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58029714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com