Cypress Component Testing cy.stub does not work correctly with RTK Query

149 views Asked by At

I am encountering a particular problem while developing a webApp based on React + RTK Query. For this project I decided to use, as much as possible, a TDD approach using Cypress and its Component Testing.

The component to be tested is composed as follows.

//mainContent.js
import { useFetchDataFromRTKQ } from '../useGetDataFromRTKQ';

function MainContent() {
  const {data} = useFetchDataFromRTKQ();
  return (
    <pre>{JSON.stringify(data, null, 4)}</pre>
  );
}
// testApi.js.js

export const testApiSlice = testServiceApi.injectEndpoints({
  endpoints: (builder) => ({

    // ...

    getDataFromRTKQ: builder.query({
      query: ({ uuid }) => ({
        baseUrl: '/my-base-url',
        url: `/test/${uuid}`,
        method: 'get',
        headers: { uuid },
      }),
    }),

    // ...

  }),
});
// useGetDataFromRTKQ.js
import { testApiSlice } from '@Src/testApi';

const { useGetDataFromRTKQQuery } = testApiSlice;
export const useFetchDataFromRTKQ = useGetDataFromRTKQQuery;

In this situation, if the MainContent component calls the wrapped function that in turn calls the RTKQ hook, we have no problems and the Cypress test works as expected

// example.cy.js (stub works)
import * as useFetch from '../../useGetDataFromRTKQ.js'

describe('Test component testing ', () => {
  beforeEach(() => {
    cy.mount(<MainContent />);
    cy.stub(useFetch, 'useFetchDataFromRTKQ').returns({ data: mockedData }).as('useFetchDataFromRTKQ STUB');
  });

  it('useFetchDataFromRTKQ called without problem', () => {
    expect(useFetch.useFetchDataFromRTKQ).to.be.called;
  });
});

Screenshot : cypressTestWorksCorrectly

Instead, if you decide to directly use the RTKQ hook in the MainComponent ( see code below), Cypress does not detect the hook invocation

// mainContent.js
import { testApiSlice } from '@Src/testApi';

const { useGetDataFromRTKQQuery } = testApiSlice;

export function MainContent() {
   const {data} = useGetDataFromRTKQQuery();

  return (
    <pre>{JSON.stringify(data, null, 4)}</pre>
  );
}
// example.cy.js (stub NOT works)
import { testApiSlice } from '@Src/testApi';
describe('Test component testing ', () => {
  beforeEach(() => {
    cy.mount(<MainContent />);
    cy.stub(testApiSlice, 'useGetDataFromRTKQQuery').returns({ data: mockedData }).as('useGetDataFromRTKQQuery STUB');
  });

  it('useFetchDataFromRTKQ called without problem', () => {
    expect(testApiSlice.useGetDataFromRTKQQuery).to.be.called;
  });
});

Screenshot : cypressTestNotWorks

What could be the source of this problem?
Is there any way to directly stub RTKQ methods?
Thanks in advance

0

There are 0 answers