用Jest测试MutationObserver [英] Testing MutationObserver with Jest
问题描述
我编写了一个脚本,其主要目的是向表的某些单元格中添加新元素.
I wrote a script with the main purpose of adding new elements to some table's cells.
测试是通过类似这样的方式完成的:
The test is done with something like that:
document.body.innerHTML = `
<body>
<div id="${containerID}">
<table>
<tr id="meta-1"><td> </td></tr>
<tr id="meta-2"><td> </td></tr>
<tr id="meta-3"><td> </td></tr>
<tr id="no-meta-1"><td> </td></tr>
</table>
</div>
</body>
`;
const element = document.querySelector(`#${containerID}`);
const subject = new WPMLCFInfoHelper(containerID);
subject.addInfo();
expect(mockWPMLCFInfoInit).toHaveBeenCalledTimes(3);
呼叫
mockWPMLCFInfoInit
时,它告诉我该元素已添加到单元格中.
mockWPMLCFInfoInit
, when called, is what tells me that the element has been added to the cell.
部分代码使用MutationObserver在向表中添加新行时再次调用mockWPMLCFInfoInit
:
Part of the code is using MutationObserver to call again mockWPMLCFInfoInit
when a new row is added to a table:
new MutationObserver((mutations) => {
mutations.map((mutation) => {
mutation.addedNodes && Array.from(mutation.addedNodes).filter((node) => {
console.log('New row added');
return node.tagName.toLowerCase() === 'tr';
}).map((element) => WPMLCFInfoHelper.addInfo(element))
});
}).observe(metasTable, {
subtree: true,
childList: true
});
WPMLCFInfoHelper.addInfo
是mockWPMLCFInfoInit
的真实版本(当然是模拟方法).
WPMLCFInfoHelper.addInfo
is the real version of mockWPMLCFInfoInit
(which is a mocked method, of course).
根据上面的测试,如果添加类似的内容...
From the above test, if add something like that...
const table = element.querySelector(`table`);
var row = table.insertRow(0);
console.log('New row added');
永远不会被调用.
可以肯定的是,我也尝试过在新行中添加所需的单元格.
console.log('New row added');
never gets called.
To be sure, I've also tried adding the required cells in the new row.
当然,手动测试告诉我该代码有效.
Of course, a manual test is telling me that the code works.
四处搜寻,我的理解是不支持MutationObserver,并且没有计划支持它.
Searching around, my understanding is that MutationObserver is not supported and there is no plan to support it.
足够好,但是在这种情况下,如何测试代码的这一部分?除了手动,就是:)
Fair enough, but in this case, how can I test this part of my code? Except manually, that is :)
推荐答案
我知道我在这里参加聚会迟到了,但是在我的玩笑设置文件中,我只是添加了以下模拟MutationObserver
类.
I know I'm late to the party here, but in my jest setup file, I simply added the following mock MutationObserver
class.
global.MutationObserver = class {
constructor(callback) {}
disconnect() {}
observe(element, initObject) {}
};
显然,这不允许您测试观察者是否做了您想要的事情,但将允许运行其余代码的测试,这是可行的解决方案的路径.
This obviously won't allow you to test that the observer does what you want, but will allow the rest of your code's tests to run which is the path to a working solution.
这篇关于用Jest测试MutationObserver的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!