RMT
RMT

Reputation: 1162

Shallow test React branch Jest and Enzyme

There are three things I want to figure out. For now I am using shallow render. I use Enzyme and Jest.

  1. I am wondering how I can test the branches in my React component. I would like to test both sides of the if-else statement (? :). And I do not want to pull it out in an own function.
  2. How can I check if this.props.myFuncFromProps(value) is been called when the input changes?
  3. What is the best practice to test mapStateToProps and mapDispatchToProps?

Here is an example of how my component would look like:

import React from 'react';
import MyChildComponent from 'wherever'; // This component is an input field in this example

export class MyComponent extends React.Component {
  render() {
    const myFunc(value) {
      this.props.myFuncFromProps(value);
    }
    
    return (
      <div>
        { this.props.isTrue ?
          <MyChildComponent
            value={this.props.value}
            onChange={(value) => myFunc(value)}
          />
          : null
        }
      </div>
    );
  }  
}

Upvotes: 0

Views: 1409

Answers (1)

Andreas K&#246;berle
Andreas K&#246;berle

Reputation: 110892

To test the different states just render your component with the different attributes and make a snapshot (note, that you have to check the first time the snapshot was created). To test event callback, you have to pass a spy function (jest.fn()) into to component and use simulate to call the event, then test that the spy was called.

describe('MyComponent', () => {
    describe('with isTrue is true', () => {
        let myComponent
        let myFuncFromProps
        beforeEach(() => {
            myFuncFromProps = jest.fn()
            myComponent = shallow(
                <MyComponent isTrue myFuncFromProps={myFuncFromProps} />
            )
        })
        it('renders correct', () => {
            expect(myComponent).matchSnapshot()
        })

        it('onchange will call myFuncFromProps', () => {
            myComponent
                .find('MyChildComponent')
                .simulate('onChange', 'someValue')
            expect(myFuncFromProps).toHaveBeenCalledWith('someValue')
        })
    })

    it('with isTrue is false it renders correct', () => {
        const myComponent = shallow(<MyComponent />)
        expect(myComponent).matchSnapshot()
    })
})

Upvotes: 1

Related Questions