【发布时间】:2022-01-05 16:08:12
【问题描述】:
我似乎无法让这个简单的测试在react-testing-library 和react-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