Shallow rendering in tests yields wrappers that yield undefined when querying props.
import React from "react";
import PropTypes from 'prop-types';
export default function MyButton(props) {
return (
<button>{props.title} {props.description}</button>
);
}
MyButton.propTypes = {
title: PropTypes.string,
description: PropTypes.string
};
import { shallow } from 'enzyme';
import React from 'react';
import MyButton from './MyButton';
it('renders without crashing', () => {
const wrapper = shallow(<MyButton title="hello" description={"hihi"}/>);
wrapper.update();
console.log(wrapper);
console.log(wrapper.prop('title'));
console.log(wrapper.prop('description'));
// expect(wrapper.prop('title')).toEqual('hello');
// expect(wrapper.prop('description')).toEqual('hihi');
});
PASS src\components\MyButton\MyButton.test.js
√ renders without crashing (7ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.586s
Ran all test suites matching /^C:.Users.saifuls.IdeaProjects.React.JavaScript.chooosie-deals-frontend-admin.src.components.MyButton.MyButton\.test\.js$/ with tests matching "^(test )?renders without crashing$".
console.log src\components\MyButton\MyButton.test.js:8
ShallowWrapper { length: 1 }
console.log src\components\MyButton\MyButton.test.js:9
undefined
console.log src\components\MyButton\MyButton.test.js:10
undefined
I expect the props 'title' and 'description' to be not-undefined, so I can assert their contents.
| library | version
| ---------------- | -------
| Enzyme | 3.3.0
| React | 16.2.0
Yeah, because the wrapper is button, not MyButton.
wrapper.type() === 'button'
@saifulss this is expected; what would be the point of asserting on the props you just passed into the wrapper 2 lines above?
@ljharb I supplied the contrived example specifically for this GitHub issue, to bring focus to the matter at hand.
First foray into testing React components. Wanted to know the capabilities of my tools. Hence this clarification.
@koba04 thanks for the tip! I'll tinker around some more to internalize this.
@saifulss is your Mybutton component is wrapped with higher order component?
Is it resolved? I am facing the same issue.
@guptadeepanshu21 there's no bug - a shallow wrapper of Foo is what Foo renders, not Foo itself.
@saifulss @guptadeepanshu21 please use wrapper.instance().props to access the props.
@ManvendraSK that won't work on an SFC in React 16+, or a memoized component, or a forwardRef.
You just passed the props in yourself, there's no need to "access" them from enzyme.
Most helpful comment
Yeah, because the
wrapperisbutton, notMyButton.