如何解决测试库 findBy* 查询仅适用于 async/await
在文档中,findBy
查询返回一个 Promise。但在将这些查询与 Promise.prototype.catch()
一起使用的情况下,这些查询似乎与 async/await + try...catch 一起使用不起作用。
例如,“未找到”按预期记录在此处:
const { screen } = require('@testing-library/dom');
beforeAll(() => {
document.body.innerHTML = `
<header></header>
`;
});
test('DOM',async () => {
try {
await screen.findByRole('aaaaa');
console.log('found');
} catch {
console.log('not found');
}
});
但是,这里没有记录任何内容:
test('DOM',() => {
screen.findByRole('aaaaa')
.then(() => {
console.log('found');
})
.catch(() => {
console.log('not found');
});
});
这有什么原因吗?
解决方法
您只需返回 Promise
,以便您的测试框架(可能是 Jest)知道等待测试完成。否则 Jest 无法知道这个测试是异步的,使用 async
关键字隐式返回一个 Promise
。
const { screen } = require('@testing-library/dom');
test('DOM',() => {
return screen.findByRole('aaaaa')
.then(() => {
console.log('found');
})
.catch(() => {
console.log('not found');
});
});
,
您的两个示例并不相同。语句 screen.findByRole('aaaaa')
不在 Promise 内。将函数设置为 async 会将函数包装在 Promise 中。然后,应编写与 async await 等效的代码,如下所示。
除了处理“在 Promise 中抛出错误...”的要求之外,我还修改了代码以处理函数返回错误类型的情况。
/// I added fake up implementations just for ilustration
let screen={
findByRole:
()=>new Promise((resolve,reject) => setTimeout(
()=>{reject(new Error('The error'))},2000
))
}
// You can comment above and uncomment to test different scenarios
//let screen={findByRole:()=>new Error('The error')}
//let screen={findByRole:()=>5}
function test(desc,func)
{
func()
}
/////
test('DOM',() => {
new Promise(
(resolve,reject) => {
let result = screen.findByRole('aaaaa')
result instanceof Error? reject(result):resolve(result)
})
.then(() => {
console.log('found');
})
.catch((e) => {
console.log('not found and capture error: ' + e.message);
});
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。