我正在使用模块 rn-fetch-blob
来管理 React-Native 项目中的下载。该模块提供了一个 StatefulPromise 类,它基本上是一个带有一些附加功能的 Promise。这个附加功能给我的 Jest 单元测试带来了问题。这是最初导致问题的模拟(文件 __mocks__/rn-fetch-blob.js
中的代码):
export default {
config: jest.fn(x => {
return {
fetch: jest.fn(x => Promise.resolve({ // <- I believe the problem lies here
info: () => {
return {status: 200}
}
}))
}
})
}
在我的代码中的某个地方,我引用了 StatefulPromise 方法之一(expire
)。涵盖该方法的单元测试失败并显示以下消息:
filePromise.expire 不是一个函数
。
我的想法是为了测试而创建我自己的 StatefulPromise
:
class StatefulPromise extends Promise {
expire() {
jest.fn(() => {})
}
}
...
...
...
fetch: jest.fn(x => StatefulPromise.resolve({<same logic as before>});
这并没有解决问题。
我会注意到,这在我的浏览器 JavaScript 控制台中似乎工作得很好。以下内容也让我感到惊讶:
let foo = StatefulPromise.resolve('foo');
console.log(foo instanceof StatefulPromise);
// true in console; false in jest
这让我很困惑。有没有更好的方法来解决这个问题?
最佳答案
如果类继承出错,
StatefulPromise.resolve('foo') instanceof StatefulPromise
可能为 false。如果它在某些环境中工作但在 Jest 中不起作用,这可能意味着 Jest 没有正确配置,并且类继承在不应受到 Babel 影响的情况下受到影响。这不一定是本次测试的问题,但以后可能会出现问题。
rn-fetch-blob
doesn't provide custom methods with inheritance 。即使会,这通常也不会要求在测试中复制类层次结构。正如源代码中所建议的,无需在可能随时间变化的测试中使用第三方 StatefulPromise
。由于 Promise 的行为应该类似于 ES6 Promise,因此可以用它来模拟它,并在需要时对其进行增强。
它是:
fetch: jest.fn(x => Object.assign(
Promise.resolve(...),
{ extend: jest.fn() }
)
关于javascript - 子类化并扩展 Jest 模拟的 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62370608/