Search code examples
javascriptreactjstestingreact-props

Props undefined after multiple redirects


I am attempting to refactor my React tests for code reuse such that I can return a React component via a function that accepts arguments of a component, Provider store and props to be generated.

It seems that the first function passes the email address correctly, however it doesn't work the same when creating the component itself.

Test.js

it('perform test', () => {
    const email = '123@test.com

    // define my store
    ...

    provider = getComponent(MyReactComponent, store, {email});
    ...
}

utils.js

export const getComponent = (Component, store = null, ...props) => {
    console.log({props}); // returns { props: [ { email: '123@test.net' } ] }

    const mockStore = configureStore();
    return <Provider store={mockStore(store)}><Component {...props}/></Provider>;
}

MyComponent.jsx

const MyComponent = ({email}) => {
    console.log({email}); // returns undefined
    ...

Solution

  • Change

    export const getComponent = (Component, store = null, ...props) => {
    

    To

    export const getComponent = (Component, store = null, props) => {
    

    Props are not meant to be spread as an array. The way it works with your present code is that you are probably getting object {email: '123@test.net'} under prop 0 (due to it being under 0th index in array)