gpt4 book ai didi

javascript - Jest 模拟 document.createRange

转载 作者:搜寻专家 更新时间:2023-11-01 04:13:37 26 4
gpt4 key购买 nike

Jest,通过我想象的 JSDom,没有定义 document.createRange。我如何覆盖或提供此行为?

我们为自定义 JSDom + mocha 设置(在所有测试之前运行)编写的版本如下所示:

global.Range = function Range() {};

const createContextualFragment = (html) => {
const div = document.createElement('div');
div.innerHTML = html;
return div.children[0]; // so hokey it's not even funny
};

Range.prototype.createContextualFragment = (html) => createContextualFragment(html);

// HACK: Polyfil that allows codemirror to render in a JSDOM env.
global.window.document.createRange = function createRange() {
return {
setEnd: () => {},
setStart: () => {},
getBoundingClientRect: () => {
return { right: 0 };
},
getClientRects: () => [],
createContextualFragment,
};
};

有没有办法提供这个来开 Jest ?

最佳答案

我在 setupTests.js 中添加了 polyfill,如 thread 中所述.

if (window.document) {
window.document.createRange = () => ({
setStart: () => {},
setEnd: () => {},
commonAncestorContainer: {
nodeName: 'BODY',
ownerDocument: document,
},
});
}

为了让它与 TypeScript 一起工作,我必须在 commonAncestorContainer 之上添加 //@ts-ignore

关于javascript - Jest 模拟 document.createRange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42213522/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com