0

我第一次尝试 [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>

测试文件(首选反应测试库):


   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

4

1 回答 1

0

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

即使我试图模拟一个错误,我也需要使用 mockResponse() 函数。

fetchMock.mockResponse( JSON.stringify({ error: "Cannot read property 'state' of null" }), { status: 500 } )

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

由于某种原因,mockReject() 函数对错误主体的外观做出了假设,并且它与我的错误看起来非常不同。

于 2022-02-25T16:40:14.393 回答