samedi 2 novembre 2019

How to mock setState for API test

I have built a react component api that I would like to test. The api is independent of the react useState hook for testing purposes. As such, my api is fed state and setState from a custom hook that I created called useAPI:

const useAPI = (api, initialState) => {
    const [state, setState] = useState(initialState)
    return api({ state, setState })
}

and an abridged, simplified example of my api is like this:

const anAPI = ({state, setState}) => {
    const name = state.name
    const surname = state.surname

    const updateName = (newValue) => {
        setState(prevState => (
            {...prevState, name: newValue}
        )) 
    }
}

I would like to test this api without using any hooks. However, I'm not sure how to mock the setState function so that I can pass it into my api and have it work properly. A simplified test file might look like this:

const state = {name: "", surname: ""}

const setState = someFunction...

const api = anAPI({state, setState})

it("updates name", () => {
    api.updateName("john")
    expect(api.name).toEqual("john")
})

What does setState need to look like in order for this test to work?

Aucun commentaire:

Enregistrer un commentaire