how to access props in mocha test in react

Viewed 22

I am trying to access props in my current test cases but once I get an instance from the wrapper class, props is getting null which is failing the test case

I tried the props() method to access the props but no luck so far. Is there any other way I can access props and test in the mocha?

Below is my code

import React from 'react'


const Button = ({children,label,onClick,type,btnClass,disabled,..rest})=>{
  let button = onClick ? (
    <button type={type} className={btnClass} onClick={onClick} 
    disabled={disabled} {...rest}>
      <span className="flex flex-row justify-center">
         {children}
         {label}
        </span>
        </button>
  ): (<button type={type} className={btnClass} 
    disabled={disabled} {...rest}>
      <span className="flex flex-row justify-center">
         {children}
         {label}
        </span>
        </button>)

        return <span>{button}</span>
};

export default Button;

Test Case:

import {mount} from 'enzyme';
import {expect} from 'chai'
describe("button component", () => {
  it("props should be available", () => {
    let props = {
      label: 'default',
      onClick: ()=>{return;}
    };
    const wrapper  = mount(<Button {...props} />);

    expect(wrapper.instance().props.label).to.be(props.label);
  });
});

Error: enter image description here

1 Answers

Have you tried with shallow instead of mount? and also replacing to.equal for toEqual.

import {shallow} from 'enzyme';
import {expect} from 'chai';
describe("button component", () => {
  it("props should be available", () => {
    let props = {
      label: 'default',
      onClick: ()=>{return;}
    };
    const wrapper  = shallow(<Button {...props} />);

    expect(wrapper.instance().props.label).toEqual(props.label);
  });
});
Related