msw: undefined response when mocking axios get

Describe the bug

I have a server.get set up to listen to a request url but whenever I am running the tests, I seem to end up with undefined in my response

Environment

  • msw": "^0.19.3
  • nodejs: 12.13.0
  • npm: 6.12.0

To Reproduce

Steps to reproduce the behavior:

  1. Run Test
  2. Check to see if component is rendered correctly
  3. See that loading component is still there.

Expected behavior

I should be able to intercept the request and consume the payload I give ctx

Screenshots

  rest.get('*', req => console.log(req.url.href)),
  rest.get(`/api/portfolioCalls`, (req, res, ctx) => {
    return res(ctx.status(200), ctx.json(propertiesData))
  }),
)
describe('PortfolioReport', () => {
  beforeAll(() => server.listen())
  afterAll(() => server.close())
  afterEach(() => server.resetHandlers())

  const checkForUserActivity = jest.fn()
  const switchToPropertyView = jest.fn()
  const setDateRange = jest.fn()
  beforeEach(() => {})

  it('should render component', async () => {
    act(() => {
      render(
        <UserContextProvider user={userData}>
          <PortfolioReport
            checkForUserActivity={checkForUserActivity}
            switchToPropertyView={switchToPropertyView}
            setDateRange={setDateRange}
          />
        </UserContextProvider>
      )
    })
    const { getByText } = screen
    expect(getByText('Portfolio')).toBeInTheDocument()
    await wait(() => {
      expect(getByText('Total Calls')).toBeInTheDocument()
    })

    screen.debug()
  })
})

this is the axios call i am trying to listen to

 try {
        const result = await axios.get(
          `${HOSTNAME}/api/portfolioCalls?startDate=${startDate}&endDate=${endDate}`
        )
        if (result?.status === 200 && result?.data) {
          const formattedData = formatData(result.data)
          dispatch({
            type: FETCH_PORTFOLIO_SUCCESS,
            payload: formattedData.properties,
            status: SUCCESS,
          })
          setData(formattedData)
        } else setData({})
      } catch (error) {
        dispatch({ type: FETCH_PORTFOLIO_ERROR, status: ERROR })
        console.log(error)
      }
    }

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 1
  • Comments: 16 (7 by maintainers)

Most upvoted comments

ok so i fixed it. i forgot when i was switching from jest.mock('axios') to msw i forgot to remove the jest.mock('axios') in my setUpTest.js

I ran into the same issue and turned out some other dev decided to mock axios globally through a setupTests.js file. I had to requireActual in my test to get a response from msw.

jest.mock('axios', () => {
  return {...jest.requireActual('axios')};
});

I haven’t done this before but I hope this is helpful! https://github.com/lammypham/msw-lammypham