score:11
what i essentially did was bring in my redux
store (and provider
) and wrapped it in a utility component as follows:
export const customprovider = ({ children }) => {
return (
<provider store={store}>
{children}
</provider>
);
};
then, i mount
the samplecomponent
and run tests against it:
it('contains <childcomponent/> component', () => {
const wrapper = mount(
<customprovider>
<samplecomponent {...defaultprops} />
</customprovider>
);
expect(wrapper.find(childcomponent)).to.have.length(1);
});
score:0
in an attempt to make the use of decorator syntax more testable i made this: https://www.npmjs.com/package/babel-plugin-undecorate
input:
@anyoldclassdecorator
export class anyoldclass {
@anyoldmethoddecorator
method() {
console.log('hello');
}
}
output:
@anyoldclassdecorator
export class anyoldclass {
@anyoldmethoddecorator
method() {
console.log('hello');
}
}
export class __undecorated__anyoldclass {
method() {
console.log('hello');
}
}
hopefully this can provide a solid option 3!
score:3
you can use name export to solve this problem:
you should have:
class samplecomponent extends react.component{
...
render(){
<div></div>
}
}
export default connect(mapstatetoprops, mapdispatchtoprops)(samplecomponent)
you can add a export before class:
export class samplecomponent extends react.component{
and import this component with no redux store:
import { samplecomponent } from 'your-path/samplecomponent';
with this solution you don't need to import store to your test files.
score:4
option 1)
you can wrap the container component with react-redux's provider component within your test. so with this approach, you actually reference the store, pass it to the provider, and compose your component under test inside. the advantage of this approach is you can actually create a custom store for the test. this approach is useful if you want to test the redux-related portions of your component.
option 2)
maybe you don't care about testing the redux-related pieces. if you're merely interested in testing the component's rendering and local state-related behaviors, you can simply add a named export for the unconnected plain version of your component. and just to clarify when you add the "export" keyword to your class basically you are saying that now the class could be imported in 2 ways either with curly braces {} or not. example:
export class mycomponent extends react.component{ render(){ ... }}
...
export default connect(mapstatetoprops, mapdispatchtoprops)(mycomponent)
later on your test file:
import mycomponent from 'your-path/mycomponent'; // it needs a store because you use "default export" with connect
import {mycomponent} from 'your-path/mycomponent'; // don't need store because you use "export" on top of your class.
i hope helps anyone out there.
score:4
there is also the option to use redux-mock-store.
a mock store for testing redux async action creators and middleware. the mock store will create an array of dispatched actions which serve as an action log for tests.
the mock store provides the necessary methods on the store object which are required for redux. you can specify optional middlewares and your app specific initial state.
import configurestore from 'redux-mock-store'
const middlewares = []
const mockstore = configurestore(middlewares)
const initialstate = {}
const store = mockstore(initialstate)
const wrapper = mount(<samplecomponent store={store}/>)
score:43
enzyme's mount takes optional parameters. the two that are necessary for what you need are
options.context: (object [optional]): context to be passed into the component
options.childcontexttypes: (object [optional]): merged contexttypes for all children of the wrapper
you would mount samplecomponent
with an options object like so:
const store = {
subscribe: () => {},
dispatch: () => {},
getstate: () => ({ ... whatever state you need to pass in ... })
}
const options = {
context: { store },
childcontexttypes: { store: react.proptypes.object.isrequired }
}
const _wrapper = mount(<samplecomponent {...defaultprops} />, options)
now your samplecomponent will pass the context you provided down to the connected component
.
Source: stackoverflow.com
Related Query
- Nested components testing with Enzyme inside of React & Redux
- Testing functions inside stateless React component with Enzyme
- Getting started testing React components with Enzyme and Jest
- Testing components that contain react router Link with Enzyme
- Testing react components that have JSS injected styles with enzyme
- Testing react components with redux-toolkit inside
- Testing React components with Enzyme when component uses events
- Unit Testing with Mocha,Enzyme dispatched functions in functional components which uses React Hooks + Redux
- Rendering React components with promises inside the render method
- Cannot read property '.then' of undefined when testing async action creators with redux and react
- Accessing the State of a Functional Component with React Hooks when Testing with Enzyme
- Testing React portals with enzyme
- React - Create nested components with loops
- React Hook Form: Submit a form with nested components or extract fields of nested components to submit
- reactjs - jest snapshot testing nested redux "connected" components
- Mock React useRef or a function inside a functional component with enzyme and jest?
- React testing component prop change with enzyme
- Connecting nested Redux smart components with reducers
- Testing debounced function in React component with Jest and Enzyme
- _this.store.getState is not a function when testing react component with enzyme and mocha
- Testing react-intl components with enzyme
- Communication between two React form components with Redux
- How to test components internal functions with React testing library
- How to test inner functions defined on Stateless Components in React with Enzyme
- Find element with Enzyme in nested React component
- Testing React Component className with enzyme
- How to test Material-UI's Responsive UI (e.g. Hidden, Grid, Breakpoints) in React with Enzyme or React Testing Library
- Testing react router v4 with jest enzyme
- Testing Webpack built React components with Jest
- Sync queryParameters with Redux state and react router for function components
More Query from same tag
- reactjs compilation error 'e' is undefined no-undef in specific scenario
- How can I display dynamic state in react
- Why is this JS error thrown?
- React props being sent to a component appear as an empty array
- React sibling communication with ONLY access to parent
- How to update button width without css ReactJs
- What is wrong with my basic ReactJS app?
- Someone who knows CanvasRenderingContext2D in React, please help :)
- How to hide/show column based on if statement using Material-ui?
- how to sort an array by string and number and date property using reactjs?
- Error: Must use destructuring state assignment in react using Websoket
- State incrementing by more than expected
- Filtering js array of objects based on more than one property
- How can I render a container / component based on the route using react-router?
- React switching between components or hiding and transitions
- ANT Design Push Pull Confusion
- Can't mock a library value when snapshot testing with jest
- How can I open a rect-bootstrap modal dialog from another Component
- Redux state is not persisting
- passing data to componnet onClick in react js
- functional component rerender on state change
- React server side rendering - support for hashbang
- Why must I use the spread operator in this JSX element?
- Show/hide a message if date time match with API response
- TypeError: Cannot set properties of undefined (setting 'duration')
- How do I work with Redux/React in Kotlin.js?
- How to fix redirects frontend url and api url in laravel?
- useEffect wont run when state gets changed
- Using ReactCSSTransitionGroup with styled-component
- How to edit the styling of multple elements in React.js