I am using the @cypress/react
package to perform unit-testing on react components.
In my case, these react components contain external influence such as services or redux state management.
I tried to stub these external components with cy.stub()
but I get an error that I don't know how to work around.
Example:
I have a component that invokes useSelector
from redux in order to get the current state currentState
. It looks like the following:
import { currentStateSelector } from 'store/current-state/selectors';
export default function MyComponent() {
const currentState = useSelector(currentStateSelector);
return (
currentState !== null ?
<div data-testid='my-component'>
{ currentState.name }
</div>
:
<></>
);
}
In order to test this I created the following spec file:
import React from 'react';
import mount from '@cypress/react/dist';
import MyComponent from './my-component';
import * as reactRedux from 'react-redux';
import { store } from '../../store';
describe('MyComponent',() => {
it('renders', () => {
const useSelectorMock = cy.stub(reactRedux, 'useSelector');
const currentState = {
name: 'test',
};
useSelectorMock.returns(currentState);
mount(
<reactRedux.Provider store={store}>
<MyComponent/>
</reactRedux.Provider>
);
cy.get('[data-testid=my-component]').should('exist');
});
});
Running the test with npx cypress open
it gives me an AssertionError:
Timed out retrying after 4000ms: Expected to find element: [data-testid=my-component], but never found it.
Apparently, the element that I tried to stub returns a null value, which is why this AssertionError occured. But how do I resolve this?
Maybe I have not understood the stubbing functionality fully yet, but after days of research I haven't found anything helpful. Any help would be much appreciated.
UPDATE
I switched to the test framework jest and the mocking works by writing the following before describe(...)
:
jest.mock('react-redux', () => ({
useSelector: jest.fn( () => { return 'desired return-object' })
}));