【发布时间】: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
尝试 1:yarn 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