1

Folks, Front-end newb here. Trying to understand how to properly pass mock props to a constructor of a component....

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        let dataToDecode = QueryString.parse(props.location.search).data;
        const data = QueryString.parse(Base64.decode(dataToDecode));
        this.state = {
            email: data.email,
            ...
        };
    ...

So how does one mock the props in react? can testing-library/react or jest help with this?

i.e. the tests need to cover proper uri and an incorrect one.
https://domain/path?data=somebase64encodedstring

it('renders without crashing', () => {
    const div = document.createElement('div');
    ReactDOM.render(<MyComponent />, div);
});

thanks!

1 Answer 1

1

I would recommend you to make use of the Enzyme library, which allows you to shallow render or fully render your component. Enzyme allows you to easily test your component's output.

In this scenario, it will be sufficient to use shallow rendering.

This is one way you can shallow render your components with your mocked props.

import * as React from 'react';
import { shallow } from 'enzyme';

describe('<MyComponent />', () => {

  it('sample test', () => {
    const myComponent = <MyComponent 
      location={mockLocation} 
      otherProps={otherMockProps}
    />
    const wrapper = shallow(myComponent);
    // expect().....
  });

})

As you can see from the above, we called the shallow rendering API, shallow(), on your component together with the required props. From there onwards, you can carry out other forms of behaviour, such as calling of methods, or spying on method calls, and test for the desired behaviour.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.