问题描述
我已经使用 JavaScript 成功创建并注入了我的样式表,我的功能没有问题,但我的测试现在没有通过,因为我收到了这个错误
TypeError: Cannot set property 'parentStyleSheet' of undefined
.
当我运行测试和 console.log(stylesheet)
时,它确实返回为 null
。
我什至无法进入测试的第一行,因为我一开始就收到了这个错误。
如果我注释掉我的 insertRule()
,则测试通过。
如何模拟此样式表,以便让我的测试再次通过?
我创建样式表的函数:
const createStyleSheet = () => {
this.createdStyleSheet = (function () {
const style = document.createElement('style');
style.title = 'carousel';
style.appendChild(document.createTextNode(''));
document.head.appendChild(style);
return style.sheet;
}());
};
createStyleSheet();
this.createdStyleSheet.insertRule(---stuff inside here---);
解决方法
我这样做是为了模拟 insertRule。如果您只是想阻止它因未定义而失败,这将起作用。如果您确实需要为将来的测试添加样式,那么您可能需要修改它。我只返回 0 以阻止我的打字稿抱怨
window.CSSStyleSheet.prototype.insertRule = function (rule,index) {
const styleElement = document.createElement("style");
const textNode = document.createTextNode(rule);
styleElement.appendChild(textNode);
document.head.appendChild(styleElement);
return 0;
};
使用此链接查看需要放置模拟函数的位置
https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom