【问题标题】:TypeScript - Is there a way in Jest to mock/spyOn the document.fonts API?TypeScript - 在 Jest 中有没有办法模拟/监视 document.fonts API?
【发布时间】:2022-03-20 19:19:32
【问题描述】:

有没有办法让这个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,例如根据this SO

flow(由于遗留原因,如果有帮助,可以用 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'.

这通常被// @ts-ignore TS2339 静音,这对大多数人来说可能已经足够了。但是,有时我们会很好奇:D


尝试 1yarn add -D @types/css-font-loading-module(感谢 all contributing here!)只会触发不同的后续警告:

TS2739: Type '{ then: Mock<any, any>; }' is missing the following properties 
from type 'Promise<FontFaceSet>': catch, [Symbol.toStringTag], finally 

不幸的是,这似乎导致了更多错误的兔子洞......


尝试 2:我受到this post on mocking global.window with jest 的启发,尝试了一些至少看起来合理的事情(结合上面的尝试 1):

jest.spyOn(global.document.fonts, 'ready', 'get')

但是这会导致测试无法运行Cannot spyOn on a primitive value; undefined given

探索 jsdom,例如here 建议 document.fonts 尚未实现。所以我现在很难过。

【问题讨论】:

  • 那么如果jsdom中没有实现,为什么不@ts-ignore呢?

标签: typescript unit-testing jestjs


【解决方案1】:

在您的setupFiles 之一中添加以下代码:

Object.defineProperty(document, 'fonts', {
  value: { ready: Promise.resolve({}) },
})

【讨论】:

  • 奇怪的是,这在我的笔记本电脑上运行良好,但在 AWS CodeBuild 上使用 registry.hub.docker.com/library/node:14 时 eslint@^7 失败,错误代码为 137。不过谢谢你,在没有更多信息的情况下,这仍然是一个很好的答案。
猜你喜欢
  • 1970-01-01
  • 2017-09-02
  • 2022-07-15
  • 1970-01-01
  • 1970-01-01
  • 2020-08-14
  • 2021-09-11
  • 2011-07-24
  • 2011-02-23
相关资源
最近更新 更多