【问题标题】:Catch problem with await in React 17, jest and testing library在 React 17、jest 和测试库中使用 await 捕获问题
【发布时间】: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


【解决方案1】:

正如一些人评论的那样,我认为这是一个 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

【讨论】:

    猜你喜欢
    • 2020-03-24
    • 2021-06-14
    • 2020-06-14
    • 2020-06-01
    • 2021-09-20
    • 2021-07-27
    • 2019-04-22
    • 2020-10-12
    • 2021-06-04
    相关资源
    最近更新 更多