question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

undefined response when mocking axios get

See original GitHub issue

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)
      }
    }

Issue Analytics

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

github_iconTop GitHub Comments

2reactions
lammyphamcommented, Jul 14, 2020

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

1reaction
lammyphamcommented, Jun 19, 2020

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

Read more comments on GitHub >

github_iconTop Results From Across the Web

Why does mocked axios get method return undefined?
So after some experimentation, it would appear that the jest.mock("axios") call was interfering with the jest.spyOn(axios, "get"); call.
Read more >
axios typeerror: cannot read properties of undefined (reading ...
I developing my final project using React with TypeScript and I'm trying to test a mocked response using Jest but I just get...
Read more >
Jest axios mock returning undefined in expected response ...
How can I mock multiple get axios request in Jest unit test for an async action that calls a few more async actions?...
Read more >
Mocking asynchronous functions with Jest - SwC
Mock Axios with no return. The res (response) variable we are looking for in our .then callback is undefined and therefore we cannot...
Read more >
Cannot read property of undefined with Axios, Jest - Vue Forum
I mocked my axios with jest.mock(“axios” …). I return a Promise. I defined a commit and the response of my axios request. But...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found