我在测试中遇到问题:
这是我的代码:
test("should render text component", async () => {
render(<TextComponent />)
const headings = await screen.findAllByRole("heading")
expect(headings.length).toBe(1)
})
测试通过,但是react编译器或lint说:
src / components / customcomponents / factory / ComponentFactory.test.jsx 7:9行:应返回承诺以测试其实现或拒绝。开玩笑/有效期望承诺
好吧,似乎我需要抓住,所以:
test("should render text component", async () => {
render(<TextComponent />)
const headings = await screen.findAllByRole("heading").catch(expect(false))
expect(headings.length).toBe(1)
})
测试再次通过,但是出现了新的编译器错误:
src / components / customcomponents / TextComponent.test.jsx 8:32行:
findAllByRole
必须具有await
个运算符testing-library / await-async-query
好,让我们尝试try ... catch:
test("should render text component", async () => {
render(<TextComponent />)
try {
const headings = await screen.findAllByRole("heading")
expect(headings.length).toBe(1)
} catch (err) {
expect(err).toBeTruthy()
}
})
测试通过...但是我有一个新错误!
src / components / customcomponents / TextComponent.test.jsx 12:13行:避免有条件地调用
expect
开玩笑/无条件期望
那么...对此有什么解决方案?什么是正确的代码?
谢谢大家!
答案 0 :(得分:0)
正如某些人所评论的那样,我认为这是一个ESLint问题,代码没有问题,但是我有一些有效和ESLint 喜欢的代码:>
test("should render text component", async () => {
render(<TitleComponent />)
let headingLength = 0;
try {
const headings = await screen.findAllByRole("heading")
headingLength = headings.length
} catch (err) { }
expect(headingLength).toBe(1)
})
上面的代码可以正常工作,通过并且不会对ESLint造成问题。缺点是我讨厌let
。