测试库findBy*查询仅适用于async/await



从文档中,findBy查询返回一个Promise。但似乎使用这些查询与Promise.prototype.catch()不工作的情况下,使用他们与async/await + try…抓住。

例如,'not found'按预期记录在这里:

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等价的语句应该写成如下所示:

我已经调整了代码,以处理函数返回错误类型的情况下,除了你的要求,以处理"抛出一个错误在一个承诺…">

/// 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);
});
});

最新更新