criver.to
criver.to

Reputation: 540

Setting state in React Enzyme unit test which I pass through props

I am using Enzyme to test the component below and I get the following error:

selectedAccount: props.accounts[0].id
TypeError: Cannot read property '0' of undefined

As you can see in the component below the selectedAccount is in the state which gets its value from the props, which I set in the unit test.

class Modal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedAccount: props.accounts[0].id
    };
  }

  render() {
    const {selectedAccount} = this.state;

    return <div>
              <p>
               {selectedAccount}
              </p>
         </div>;
  }

In my test I am passing the props which set the "selectedAccount" variable in the state.

Below is my test:

test.only('components/Modal: renders elements', t => {

  const defaultProps = { accounts: [{
        id: 1, desc: 'account1'
      }, {
      id: 2, desc: 'account2'
      }
  ]}

  const wrapper = shallow(
      <Modal/>
  ).setProps(defaultProps);

  const test = wrapper.find('p');
  t.equal(test.length, 1, 'should render 1 p element ');
  t.end();

 });

Why is the state not being set from the props I'm passing which include an accounts array with id and desc properties?

Upvotes: 1

Views: 1937

Answers (1)

Amberlamps
Amberlamps

Reputation: 40448

.setProps() is injecting properties and re-renders. This is to simulate changing properties over time. If you want that property to be available during construction, pass it as a property as you are used to:

const wrapper = shallow(
  <Modal accounts={defaultProps.accounts} />
)

Upvotes: 2

Related Questions