首页 > 解决方案 > 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尚未实现。所以我现在很难过。

标签: typescriptunit-testingjestjs

解决方案


推荐阅读