score:0
the problem is with mocking useselector
. the function itself pass appstate
to a callback, but a mock function is not aware of appstate
. in this way your mock will return undefined. in this way books
(list) will be undefined
.
you need to specify what your mock will return, in this case an array. you can call mockreturnvalue
passing a booksmock (an array) for that:
jest.mock("react-redux", () => ({
useselector: jest.fn().mockreturnvalue(booksmock),
usedispatch: () => mockdispatch
}));
score:0
you should mock the return value of useselector
hook.
e.g.
gridcontainer.tsx
:
import react, { useeffect } from 'react';
import { usedispatch, useselector } from 'react-redux';
import { getdata } from './actions/index';
import { appstate } from './store/store';
import griditem from './component/griditem';
function gridcontainer() {
const dispatch = usedispatch();
const books = useselector((state: appstate) => state);
console.log('books:', books);
useeffect(() => {
dispatch(getdata());
}, [dispatch]);
const booklist = (list: appstate) => {
return list.map((book) => <griditem key={book.id} data={book} />);
};
return <div classname="book-container">{booklist(books)}</div>;
}
export default gridcontainer;
./component/griditem.tsx
:
import react from 'react';
export default function griditem({ data }) {
return <div>{data.name}</div>;
}
./store/store.ts
:
export type appstate = any[];
./actions/index.ts
:
export function getdata() {
return { type: 'get_data' };
}
gridcontainer.test.tsx
:
import react from 'react';
import { shallow, mount } from 'enzyme';
import gridcontainer from './gridcontainer';
import { usedispatch, useselector } from 'react-redux';
const mockdispatch = jest.fn();
const booksmock = [
{ id: 1, name: 'golang' },
{ id: 2, name: 'typescript' },
];
jest.mock('react-redux', () => {
return {
useselector: jest.fn(() => booksmock),
usedispatch: jest.fn(() => mockdispatch),
};
});
describe('react hooks', () => {
aftereach(() => {
jest.clearallmocks();
});
it('renders container', () => {
const wrapper = shallow(<gridcontainer />);
const component = wrapper.find('.book-container');
expect(component.length).tobe(1);
});
it('runs dispatch on mount', () => {
const wrapper = mount(<gridcontainer />);
expect(usedispatch).tobecalledtimes(1);
expect(useselector).tobecalledwith(expect.any(function));
expect(mockdispatch).tobecalledwith({ type: 'get_data' });
expect(wrapper.find('.book-container').children()).tohavelength(2);
});
});
unit test result:
pass examples/65172098/gridcontainer.test.tsx
react hooks
✓ renders container (65 ms)
✓ runs dispatch on mount (44 ms)
console.log
books: [ { id: 1, name: 'golang' }, { id: 2, name: 'typescript' } ]
at gridcontainer (examples/65172098/gridcontainer.tsx:11:11)
console.log
books: [ { id: 1, name: 'golang' }, { id: 2, name: 'typescript' } ]
at gridcontainer (examples/65172098/gridcontainer.tsx:11:11)
--------------------|---------|----------|---------|---------|-------------------
file | % stmts | % branch | % funcs | % lines | uncovered line #s
--------------------|---------|----------|---------|---------|-------------------
all files | 95 | 100 | 85.71 | 100 |
65172098 | 93.33 | 100 | 80 | 100 |
gridcontainer.tsx | 93.33 | 100 | 80 | 100 |
65172098/actions | 100 | 100 | 100 | 100 |
index.ts | 100 | 100 | 100 | 100 |
65172098/component | 100 | 100 | 100 | 100 |
griditem.tsx | 100 | 100 | 100 | 100 |
--------------------|---------|----------|---------|---------|-------------------
test suites: 1 passed, 1 total
tests: 2 passed, 2 total
snapshots: 0 total
time: 5.442 s
source code: https://github.com/mrdulin/jest-v26-codelab/tree/main/examples/65172098
Source: stackoverflow.com
Related Query
- array is undefined in component being rendered with enzyme?
- How to test styles and media queries rendered by a React component with Jest and/or Enzyme
- Collect Data from the same component which is being rendered multiple times into an array to be sent to the server
- In React, how do I call a function in one component (which is being rendered with React Router) from another component?
- React Hooks useState Array empty with states rendered in the component
- React functional component with non-JSX class has an internal array returning undefined
- Testing ReactJS component methods with enzyme shallow - function returns undefined instead of true
- Material-UI component not being rendered with react-rails prerender
- React component being rendered with old props
- Enzyme Shallow Rendered Component is Undefined
- Map function returns array with undefined elements in React component
- Passing an array of objects to child component rendered within iteration returns undefined error in React
- How to mock React component methods with jest and enzyme
- How to test style for a React component attribute with Enzyme
- How to test if a component is rendered with the right props when using react-testing-library?
- Accessing the State of a Functional Component with React Hooks when Testing with Enzyme
- Check if child component rendered - Jest, Enzyme
- Find component by display name when the component is stateless functional, with Enzyme
- Incorrect casing error with dynamically rendered component in React
- Test the content of an <iframe> in a React component with Enzyme
- Storybook JS Interaction Testing with Enzyme - State Changes being Overidden
- Testing functions inside stateless React component with Enzyme
- How to mock API calls made within a React component being tested with Jest
- React Enzyme Jest test component with className
- How do I pass props a component rendered with Enzyme.js?
- Jest - How to find rendered DOM component with id?
- Mock React useRef or a function inside a functional component with enzyme and jest?
- Checking props of a child component with shallow rendering using enzyme
- React testing component prop change with enzyme
- Enzyme render styled component with theme
More Query from same tag
- A component is changing the uncontrolled value state of Select to be controlled
- React/Typescript: Selected items counter logic
- Compare 2 immutable lists for equality
- How to create a specified callback function for a setState in React Functional Component
- Error with redux-promise : Actions must be plain objects. Use custom middleware
- React Query doesn't seem to be caching
- React context is returning undefined
- React does not render when Metamask installed
- Why is react-router-dom <Redirect> not working?
- this.props.function is not a function - React js
- FormData object from React doesnt convert on backend C# to model
- React Private Routing through id
- Is the following form of functional components valid?
- How to select svg child element of a div using d3 select
- Error:Could not find method getCompileConfiguration() for arguments [] on object of type com.android.build.gradle.internal.api.ApplicationVariantImpl
- Always stumble on this error Cannot read property 'map' of undefined
- How to Drag/Drop Material-UI Cards
- React.js check if user is logged in after redirect and display a popup
- How to integrate a react application in drupal 8, using drupal custom module?
- Unit testing entry file in React
- How to iterate over multiple arrays in a JSON object in react
- JSX dot notation with forwardRef typescript
- How to use React BluePrint components with TypeScript?
- How to test if a function set something to localStorage with Jest?
- React set provider variables on application load
- How to use Typography as a styled component in react of material UI
- What is the best way to merge styles when wrapping Fabric components?
- How to center login form in web page/browser using Antd?
- Component not passing props to other component in same file when calling as const
- Import default with alias