简体   繁体   中英

React - Testing w/ Jest - TypeError: Cannot read property 'destroy' of undefined

Writing tests for a page that's relying on a lot of hooks and I'm not very experienced with testing code. On top of that, even less experience mocking the hooks involved (useSelector, useEffect, etc) The page will spawn a drawer from the bottom of the screen to select options. When the drawer is closed, my test is failing with an error of "TypeError: Cannot read property 'destroy' of undefined" and pointing to the makeStyles hook used by Material UI to defined styling rules, but it does look like theme provider is providing the styling rules so i'm not sure the issue. Need some help if anyone has insight.

import { Provider, useSelector } from 'react-redux';
import thunk from 'redux-thunk';
import configureStore from 'redux-mock-store';
import DisplayPage from './DisplayPage';

jest.mock('react-redux', () => ({
 ...jest.requireActual('react-redux'),
 useDispatch: () => jest.fn(),
 useSelector: jest.fn(),
}));
jest.mock('../../hooks', () => ({
 useDisplaySkuTracker: jest.fn(() => ({ isAvailable: [], notAvailable: [] })),
}));
describe('DisplayPage', () => {
 const middlewares = [thunk];
 const mockStore = configureStore(middlewares);
 const initialState = {
 productsModule: {
 skuTracker: {
 sorting: '',
 searchBy: '',
 filter: false,
 },
 },
 };
 const store = mockStore(initialState);
 beforeEach(() => {
 useSelector.mockImplementation((callback) => {
 return callback(initialState);
 });
 });
 it('Drawer calls `onClose`', () => {
 const useState = jest.spyOn(React, 'useState');
 const useEffect = jest.spyOn(React, 'useEffect');
 const setDrawer = jest.fn();
 useState.mockImplementationOnce((f) => [f, setDrawer]).mockImplementationOnce((f) => [f, jest.fn()]);
 useEffect
 .mockImplementationOnce((f) => f())
 .mockImplementationOnce((f) => f())
 .mockImplementationOnce((f) => f());
 const wrapper = mount(
 <MuiThemeProvider theme={theme}>
 <Provider store={store}>
 <DisplayPage />
 </Provider>
 </MuiThemeProvider>,
 );
 const drawer = wrapper.find('h1').at(0);
 drawer.props.onClose();
 expect(setDrawer).toHaveBeenCalledTimes(1);
 });
});```

I just needed to mock the makeStyles hook just like the other hooks. I realized while writing the question. facepalm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM