Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

267
Views
How do you test an RTKQuery endpoint using jest.spyOn

I'm trying to test RTKQuery that an endpoint has been called using jest.

I eventually want to also be able to mock what the return data will be, but first I wanted to just check that the hook had been called.

An example below where I am trying to spy on myApi for the useGetMyListQuery hook which is autogenerated.

This throws and error when it runs, can anyone help?

it('Should render', async () => {
    jest.spyOn(myApi, 'useGetMyListQuery')

    render(
      <Provider store={store}>
        <MyComponent />
      </Provider>
    )

    expect(myApi.useGetMyListQuery).toBeCalled()
})
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

I can't answer your questions on how to do this with jest mocking, but I hope I can give you some insights here nontheless - from the perspective of having written most of RTKQ and how I imagine it to be tested in a stable way:

I wouldn't use jest mocking. I would mock the API.

The reason for this being is that your mocks will assume certain return values from the RTKQ hook - and if your assumptions are wrong, you might have a nice green running test, but in reality your app will still fail.

An example of this would be using skip and not checking for isUninitialized - since that case will not come up if you are not using skip and you might just assume that you will only ever see isLoading, isSuccess and isError cases in your component. It's a perfectly valid assumption in many cases, but not always true. Mocking RTKQ would hide the resulting bug behind green tests.

Instead, I would recommend using something like mock service worker to just mock your api endpoints and let RTKQ do it's work. That is how we are testing RTKQ ourselved in our own tests - you are welcome to take a look there: RTKQ tests.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!