Emille C.
Emille C.

Reputation: 612

Test React/Redux component with Jest

I am trying to test a React component with Redux using Jest:

// components/MyComponent/index.js

class MyComponent extends React.Component {
  componentDidMount = () => {
    const { someBoolean } = this.props;
    if (someBoolean === false) {
      this.props.myFunction().then(() => myHelperFunction());
    }
  }

  render = () => {
    return <div>Something</div>;
  }
}

const mapStateToProps = (state) => {
  return { someBoolean: state.someBoolean };
}

export default connect(mapStateToProps, {
  myFunction,
})(MyComponent);

In the component, if props.myBoolean == false, will call myFunction from this Redux module:

// Redux/modules/MyModule/actions/someActions.js

export const someAction = (type) => (dispatch) => dispatch({ type });
export const myFunction = () => someAction("SOME_ACTION");

I have a helper function somewhere else:

// tools/helpers.js

export const myHelperFunction = () => { // do stuff }

Now I want to test that, if MyComponent receives someBoolean as false, it calls myFunction and then myHelperFunction:

// components/MyComponent/index.test.js

jest.mock("Redux/modules/MyModule/actions/someActions.js", () => ({
  myFunction: jest.fn(),
}));

jest.mock("tools/helpers.js", () => ({
  myHelperFunction: jest.fn(),
}));

it("should call myFunction when myBoolean is false", () => {
  const initialState = {
    myBoolean: false,
  };

  const holder = mountWithTheme(mockRedux(<MyComponent />, [], initialState));

  expect(myFunction).toHaveBeenCalled();
  expect(myHelperFunction).toHaveBeenCalled();
});

But no matter what I do, it wont pass. What is the correct way to do it?

Upvotes: 0

Views: 501

Answers (1)

Rost
Rost

Reputation: 72

Honestly, I'd suggest not to use jest's magic for mocking imports. Instead of that you can simplify tests by testing dumb components only and passing all functions as props.

it("should call myFunction when myBoolean is false", () => {
  const props = {
    myBoolean: false,
    myFunction: jest.fn(),
    myHelperFunction: jest.fn()
  };

  const holder = mountWithTheme(<MyComponent {...props}/>);

  expect(myFunction).toHaveBeenCalled();
  expect(myHelperFunction).toHaveBeenCalled();
});

And refactor a bit your component:

componentDidMount = () => {
    const { someBoolean } = this.props;
    if (someBoolean === false) {
      this.props.myFunction().then(() => this.props.myHelperFunction());
    }
  }

Upvotes: 1

Related Questions