【发布时间】:2020-07-23 07:38:13
【问题描述】:
我希望有不同的单元测试来测试我的组件的不同状态以及它与异步请求的交互。我这样做有很多困难。大多数文档都说要“模拟”触发异步状态更改的事件(即模拟组件的单击),但是,我的状态应该在组件加载时更改,而不是通过任何用户交互来更改。我看到了对act 函数(https://reactjs.org/blog/2019/02/06/react-v16.8.0.html#testing-hooks)的引用,但我不知道如何在这种情况下实现它。
这是我的功能性反应组件:
import { useRequest } from '@umijs/hooks' // Request custom hook
// An async function that does an async task to get data
async function someAsyncFunctionToFetch() => {
return Promise.resolve({data: 'data'})
}
// The functional component
export function TestComponent() {
const { data, error, loading } = useRequest(FulfillmentService.getFullfillmentServices)
const loadingMarkup = (
<p>Loading</p>
)
const errorMarkup = (
<p>Error</p>
)
const contentMarkup = (
<p>{ data }</p>
)
if (loading) {
return loadingMarkup
} else if (error) {
return errorMarkup
} else if (!isEmpty(data)) {
return contentMarkup
} else {
return <p>Some empty state</p>
}
}
这些是我想要实现的测试:
describe('TestComponent', () => {
it.todo('when data is loading the loading markup should be rendered')
it.todo('when data fetching results in an error the error markup should be rendered')
it.todo('when data fetching returns with valid data the content markup should be rendered')
it.todo('when data fetching returns an empty data object the empty state markup should be rendered')
})
【问题讨论】:
标签: reactjs unit-testing jestjs enzyme