0

I can't seem to get this simple test to work in react-testing-library & react-native-testing-library. I've tried various combinations of wrapping the render function in act, or using waitFor and other async utils, but the test never waits for the component to re-render after useEffect causes the async api call to set the new state.

Also worth noting I receive the warning: An update to TestComponent inside a test was not wrapped in act(...).`. I'm aware of this issue but no method that I've seen solved it for me.

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()
    })
  })
})
4

1 回答 1

0

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

什么对我有用:

  test('test post request', async () => {
    const { findByText } = render(<TestComponent />)
    const greeting = findByText('hello there')
    waitFor(() => expect(greeting).toBeTruthy())
  })
于 2022-01-06T10:06:13.917 回答