jeudi 20 décembre 2018

How can I inject context when testing components?

The issue I'm facing is that when I inject the context, my test is seeing the default context I set in MahContext. I've tried using Shallow, I've tried it without the context wrapper around the values and it doesn't matter. Shallow gives me an empty object, which is odd. I've also tried adding childContextTypes: { mahContext: PropTypes.object } to the second parameter in mount and shallow to no avail.

My Context (with default):

const MahContext= React.createContext({ id: 0, name: '' })

My Provider:

const MahProvider = props => (
    <MahContext.Provider value={props.value}>
        {props.children}
    </MahContext.Provider>
)

The component tree (in app.js):

<MahProvider value=({9, "Johnny Utah"})>
    <ParentOfMahComponent />
</MahProvider>

My component to test:

class MahComponent extends Component {
    ...
    async componentDidMount() {
        // for my test, results in 0 and '', the defaults
        // which causes my test to fail as there is a validity check 
        // following
        const { id, name } = this.context
    }
}

MahComponent.contextType = MahContext

My test:

const component = mount(
    <MahComponent />, 
    {
        context: {
            id: 7,
            name: "John Wick"
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire