Ulsting
Ulsting

Reputation: 491

Change Props on React Functional Component with Enzyme

Title pretty much says it, I have looked for a few hours on how to change the props on a functional component using Enzyme. I have tried wrapper.setProps({ foo: 'bar' }) but that obviously does not work for functional component. Any help would be appreciated.

Upvotes: 3

Views: 4976

Answers (1)

Lin Du
Lin Du

Reputation: 102447

.setProps() should work fine with RFC. see doc

E.g.

index.jsx:

import React from 'react';

function Foo({ name }) {
  return <div className={name} />;
}

export default Foo;

index.test.jsx:

import Foo from './';
import { shallow } from 'enzyme';

describe('61688757', () => {
  it('should pass', () => {
    const wrapper = shallow(<Foo name="foo" />);
    expect(wrapper.find('.foo')).toHaveLength(1);
    expect(wrapper.find('.bar')).toHaveLength(0);
    wrapper.setProps({ name: 'bar' });
    expect(wrapper.find('.foo')).toHaveLength(0);
    expect(wrapper.find('.bar')).toHaveLength(1);
  });
});

unit test result:

 PASS  stackoverflow/61688757/index.test.jsx (11.714s)
  61688757
    ✓ should pass (12ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.992s

package versions:

"react": "^16.13.1",
"react-dom": "^16.13.1",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"jest": "^25.5.4",
"jest-environment-enzyme": "^7.1.2",
"jest-enzyme": "^7.1.2",

Upvotes: 4

Related Questions