【发布时间】:2020-11-06 16:56:06
【问题描述】:
我在测试中遇到了问题:
这是我的代码:
test("should render text component", async () => {
render(<TextComponent />)
const headings = await screen.findAllByRole("heading")
expect(headings.length).toBe(1)
})
测试通过但反应编译器或 lint 说:
src/components/customcomponents/factory/ComponentFactory.test.jsx 第 7:9 行:应返回 Promise 以测试其履行或拒绝 jest/valid-expect-in-promise
好吧,看来我需要抓紧了,所以:
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`jest/no-conditional-expect
那么...解决方案是什么?什么是正确的代码?
谢谢大家!
【问题讨论】:
-
为什么这个测试是异步的?我的第一个倾向是删除 async / await 关键字。
-
这是 linter 而不是编译器错误,所以你正忙于取悦 ESLint。第一个 sn-p 完全没问题,任何与它相矛盾的规则都应该被禁用,因为它们不兼容。其他 sn-ps 出错了。
-
@GlenCarpenter screen.findAllByRole("heading") 返回一个承诺。
-
@EstusFlask 你说得对,我认为问题出在 ESLint。
标签: reactjs async-await jestjs eslint react-testing-library