我想断言我的代码不会抛出任何最终错误。
问题是:我的代码执行 DOM 操作,这会触发异步反应:
const slot = document.createElement('slot');
myElement.attachShadow({mode:'open'}).appendChild(slot);
// ...
slot.addEventListener('slotchange', function badFunction(){
throw "MyError";
// const observer = new MutationObserver(()=>{});
// observer.observe(null);
});
// ...
it('when input child element is removed, should not throw an error', function() {
function disconnect(){
// this will throw once slotchange is emmited
myElement.removeChild(myElement.firstElementChild);
}
expect(disconnect).not.to.throw();
});
- 工作片段:https://glitch.com/edit/#!/how-to-assert-async-throw?
- 实时样本:路径=索引.html:28:9
https://how-to-assert-async-throw.glitch.me/
代码 aboe 通过测试,即使最终会抛出错误。
试试这个,让我知道这是否可行。
const slot = document.createElement('slot');
myElement.attachShadow({mode:'open'}).appendChild(slot);
// ...
slot.addEventListener('slotchange', function badFunction(){
throw "MyError";
// const observer = new MutationObserver(()=>{});
// observer.observe(null);
});
// ...
it('when input child element is removed, should not throw an error', async function() {
async function disconnect(){
// this will throw once slotchange is emmited
await myElement.removeChild(myElement.firstElementChild);
}
expect(await disconnect()).not.to.throw();
});