redux工具包的模拟api响应错误对象



我第一次尝试[redux toolkit][1],还没有找到关于如何测试ui对api调用的响应的有用文档。

我看到有人建议使用[jest-fetch-mock][2]来嘲笑语法糖中隐藏的调用。

目前我的代码可以工作,但我找不到一个好的方法来模拟我应该从api调用中获得的500来测试特定的场景。下面是在我的RequestList.tsx文件中调用api调用的方法:

const updateAndRedirect = () => {
return updateCuration({ state, employeeId })
.unwrap()
.then((data) => proceedToLookPage(data.curation.ocpId))
.catch((e) => {
const errorMessage = e.data?.error
if (errorMessage === "Cannot read property 'state' of null") {
setHasNoRequestsInQueue(true)
} else {
setHasError(true)
}
})
}
<Container>
<Box>
{error && hasNoRequestsInQueue && (
message="No new requests to start"
})
</Box>

</Container>

测试文件(首选react测试库(:


import { fireEvent, getByText, render, waitFor } from '@testing-library/react'
import { Provider } from 'react-redux'
import { store } from 'app/store'
import RequestList from 'scenes/RequestList'
import fetchMock, { enableFetchMocks } from 'jest-fetch-mock'
import userEvent from '@testing-library/user-event' 

beforeEach((): void => {
// enableFetchMocks()
fetchMock.resetMocks()
})


describe('RequestList', () => {
it('should render a "no requests in queue" message if the call fails', async () => {
const { getByText } = render(
<Provider store={store}>
<RequestList />
</Provider>
)

fetchMock.mockReject(new Error("Cannot read property 'state' of null"))

await waitFor(() => fireEvent.click(getByText(/start new/)))
await waitFor(
() => expect(getByText('No new requests to start')).toBeInTheDocument
)

When I run this test it fails because the error being thrown looks like: 

{
status: 'FETCH_ERROR',
error: "Error: Cannot read property 'state' of null"
}
I want the error to look like: 

{
status: 500,
data: {
error: "Cannot read property 'state' of null"
}
}
So that my code declaring the const errorMessage can be run. It is looking for e.data?.error but I can't nest the mocked error message in that shape. 
Since it works locally I believe it is my mock that needs to change.
Any ideas how to mock the response better? Or a different strategy for testing rtk post requests altogether?
[1]: https://redux-toolkit.js.org/introduction/getting-started
[2]: https://github.com/wheresrhys/fetch-mock-jest

终于解决了这个问题!jot-fetch-mock的文档对用户不是很友好。

尽管我试图模拟一个错误,但我需要使用mockResponse((函数。

fetchMock.mockResponse(JSON.stringfy({error:"无法读取null"的属性"state"}(,{状态:500})

其中{ error: "Cannot read property 'state' of null" }是在网络选项卡中返回的错误消息的正文。

出于某种原因,mockReject((函数对错误体的外观进行了假设,它与我的错误外观非常不同。

相关内容

  • 没有找到相关文章

最新更新