【问题标题】:React & React Native Testing Library wait for async state update caused by useEffect on mountReact & React Native 测试库等待挂载时 useEffect 引起的异步状态更新
【发布时间】:2022-01-05 16:08:12
【问题描述】:

我似乎无法让这个简单的测试在react-testing-libraryreact-native-testing-library 中工作。我尝试了将渲染函数包装在act 中的各种组合,或者使用waitFor 和其他异步实用程序,但是在useEffect 导致异步api调用设置新状态。

另外值得注意的是,我收到了警告:An update to TestComponent inside a test was not wrapped in act(...).`。我知道这个问题,但我见过的任何方法都没有为我解决这个问题。

import React, { useEffect, useState } from 'react'
import { View, Text } from 'react-native'
import { render, waitFor } from 'test-utils'
import { rest } from 'msw'
import { setupServer } from 'msw/node'
import { useApi } from './index'

const server = setupServer(
  rest.get('http://localhost/MOCK_VAR/some-endpoint', (req, res, ctx) => {
    return res(ctx.json({ greeting: 'hello there' }))
  })
)

beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())

function TestComponent() {
  const { apiRequest } = useApi()
  const [result, setResult] = useState(null)

  useEffect(() => {
    makeApiCall()
  })

  const makeApiCall = async () => {
    const apiResult = await apiRequest({ url: '/some-endpoint' })
    console.log(apiResult.greeting) // <-- 'hello there'
    setResult(apiResult.greeting)
  }

  return (
    <View>
      <Text>{result}</Text>
    </View>
  )
}

describe('Test useApi hook', () => {
  test('test post request', async () => {
    const { findByText } = render(<TestComponent />)
    const greeting = await findByText('hello there')
    await waitFor(() => { // <-- never waits
      expect(greeting).toBeTruthy()
    })
  })
})

【问题讨论】:

  • 试试 settimeout 因为那肯定会等待
  • @Prateek 感谢您的回复,这似乎有点古怪,我想知道 API 的官方方法是什么。另外值得注意的是,我收到了警告:An update to TestComponent inside a test was not wrapped in act(...).`
  • 不确定api是否为mock。
  • @Prateek 是的,使用 msw 库。我已经注销了 api 调用的结果,它按预期工作。

标签: expo react-testing-library react-native-testing-library jest-expo


【解决方案1】:

我的问题是等待findBy 函数。从文档中说findBy* 方法已经内置了waitFor。所以只需删除await 即可解决问题。

什么对我有用:

  test('test post request', async () => {
    const { findByText } = render(<TestComponent />)
    const greeting = findByText('hello there')
    waitFor(() => expect(greeting).toBeTruthy())
  })

【讨论】:

    猜你喜欢
    • 2018-11-12
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多