typescript - TypeScript - 在 Jest 中有没有办法模拟/监视 document.fonts API?
问题描述
有没有办法让这个Jest测试document.fonts.ready
通过,例如通过添加/删除任何数量的设置/安装依赖项,而不触发或消除任何TypeScript错误/警告?
describe('Input', () => {
beforeAll(() => {
// Core part of the workaround...it seems the global prefix can also optionally be added
global.document.fonts = {
ready: {
then: jest.fn()
}
};
});
test('should render an Input', () => {
expect(renderInput()).toMatchSnapshot();
});
});
上下文:我有使用的生产原因document.fonts.ready
,例如按照这个 SO。
在流(出于遗留原因,如果有帮助,可以用 TypeScript 重写)和React类,这可以编码为:
export default class Input extends React.Component<any, any> {
constructor(props: any) {
super(props);
(document: any).fonts.ready.then(() => this.setState({
value: props.defaultValue || ''
}));
}
...
但是,当测试被引入 TypeScript 上下文时,例如通过包含(而不是模拟)该组件的Input
组件,它会立即触发TS2339: Property 'fonts' does not exist on type 'Document'.
。
这通常由 a 静音// @ts-ignore TS2339
,这对大多数人来说可能就足够了。然而,有时我们很好奇:D
尝试1:A yarn add -D @types/css-font-loading-module
(感谢所有贡献者!)仅触发不同的后续警告:
TS2739: Type '{ then: Mock<any, any>; }' is missing the following properties
from type 'Promise<FontFaceSet>': catch, [Symbol.toStringTag], finally
不幸的是,这似乎导致了更多错误的兔子洞......
尝试 2:我受到这篇关于用玩笑嘲笑的帖子的global.window
启发,尝试一些至少看起来合理的事情(与上面的尝试 1结合使用时):
jest.spyOn(global.document.fonts, 'ready', 'get')
但是,这会导致测试无法运行Cannot spyOn on a primitive value; undefined given
。
探索 jsdom,例如这里的建议document.fonts
尚未实现。所以我现在很难过。
解决方案
推荐阅读
- android - Recycler 视图中的表格布局
- swagger - 从 Swagger UI 隐藏复杂的只读属性
- flutter - Flutter Firestore Operator 未定义
- php - 如何排列现有数据并根据其优先级排序
- flutter - 如何合并数组并访问两个数组 Dart 的字段?
- hybris - Smartedit - 用户组无法上传/替换/删除组件的媒体属性而不是管理组的一部分
- c# - 为什么 JsonConvert.DeserializeObject 返回错误:异常:值不能为空。(参数“来源”)
- javascript - Next Js-getStaticProps 在一个特定的服务器上不起作用。你知道原因吗?
- ag-grid-angular - 在 ag-grid 图表中绘制垂直/水平线
- next.js - Next.js 默认是同站点来源,但我仍然可以访问它