Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test: onClick event - Jest/ Enzyeme

I am new to unit testing and I just ran a test coverage. This is the only line missing at the moment.

How could I test this line and make sure 100 % is covered

   export default class Normalize extends Component {

 constructor(props) {
super(props)
this.state = {}
 //    this.handleChange = this.handleChange.bind(this)
}

 componentDidMount() {
 this.props.normalizeData(null)    
}

 render () {
return (
  <div id='normalize-container'>
    <div id='normalize-header'>
    </div>
    <br /><br />
    <h3 className='normalized-header'>{this.props.newResponse ? 'Raw Data' : 'Normalized Data'}</h3><br/>
    <div>
      {this.props.newResponse ? null :
        this.props.THead ?
          <div>
            {!this.props.datasourceCatalog ? 
              <div id='next-button-modal'>
                {/*<button title='Proceed To Shape' className='request-button' id='next-btn-ready-modal' onClick={this.props.nextTab}><img src={nextImg}/></button>*/}
                <button title='Proceed To Shape' className='request-button' id='next-btn-ready-modal' onClick={(e) => {this.props.toggleModal(); this.props.nextTab();}}>
                  <FontAwesome
                  className='fa-angle-right'
                  name='view-externallink-img'
                  size='2x'/>                  
                </button>

                <h4>Proceed To Shape</h4>
              </div> : 
            null}

            <div className='normalize-table-container'>
              <div className="data-table-wrapper">
                <table>
                  <thead dangerouslySetInnerHTML={{__html: this.props.THead}} />
                  <tbody dangerouslySetInnerHTML={{__html: this.props.TBody}} />
                </table>
              </div>
            </div>
          </div>
        : null
      }
    </div>
  </div>

Using React JS - jest and enzyme

Testing file :

// jest mock functions (mocks this.props.func)
const normalizeData =  jest.fn();
const toggleModal =  jest.fn();
const nextTab =  jest.fn();
const onClick =  jest.fn();

// defining this.props
const baseProps = {
normalizeData,
newResponse:{},
THead:{},
TBody:{},
datasourceCatalog:{},
toggleModal,
nextTab,
onClick,

describe(' Normalize Test', () => {
let wrapper;
let tree;

beforeEach(() => wrapper = shallow(<Normalize  {...baseProps} />));

it(' Should render with all of the props', () => { 

Render with all props are working - but just need to make sure how to test the line above, on click with 2 props.

Thank you

like image 273
user 9191 Avatar asked Feb 09 '19 14:02

user 9191


People also ask

How do you test for Jest and enzymes?

Both Jest and Enzyme are meant to test the react applications. Jest can be used with any other Javascript framework, but Enzyme is meant to run on react only. Jest can be used without Enzyme, and snapshots can be created and tested perfectly fine. But the Enzyme adds additional functionality to it.

How can I test the onclick event of a button?

Okay, so after more research, I've found that the React Testing Library provides some tools to test the onClick event of some buttons (at least those that are like the ones I've shown in my example above). One of those tools is the fireEvent, which helps to accomplish what I wanted:

Why is my jest test not working?

This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax. jest Your test suite must contain at least one test. Test third party API (Stubbing). How to check whether a checkbox is checked in jQuery?

How to handle a checkbox event using React testing library?

We have also checked a checkbox using the testing library and handle a checkbox event. 1. Create a counter app Let’s create a simple counter application using the create-react-app and increment/decrement the counter using button click. 2. Write a test cases Let’s test the following test cases for the counter application.

What to do when jest failed to parse a file?

Consider using the "jsdom" test environment. Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax. jest Your test suite must contain at least one test. Test third party API (Stubbing).


1 Answers

Something like this should work:

it('should call toggleModal and nextTab functions on button click', () => {
  // Reset info from possible previous calls of these mock functions:
  baseProps.toggleModal.mockClear();
  baseProps.nextTab.mockClear();

  // Remove props that would end up hiding the button
  wrapper.setProps({
    newResponse: null,
    datasourceCatalog: null
  });

  // Find the button and call the onClick handler
  wrapper.find('#next-btn-ready-modal').simulate('click');

  // Test to make sure prop functions were called via simulating the button click
  expect(baseProps.toggleModal).toHaveBeenCalled();
  expect(baseProps.nextTab).toHaveBeenCalled();
})

Note: you can also split these into separate tests, one to test each call separately.

like image 121
Matty J Avatar answered Oct 16 '22 17:10

Matty J