【问题标题】:How to mock React setState for API test如何模拟 React setState 进行 API 测试
【发布时间】:2020-02-28 13:25:46
【问题描述】:

我已经构建了一个我想测试的反应组件 api。该 api 独立于 react useState 钩子用于测试目的。因此,我的 api 从我创建的名为 useAPI 的自定义钩子中获取状态和 setState:

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

我的 api 的一个删节简化示例如下:

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

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

我想在不使用任何钩子的情况下测试这个 api。但是,我不确定如何模拟 setState 函数,以便我可以将它传递到我的 api 并让它正常工作。简化的测试文件可能如下所示:

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

const setState = someFunction...

const api = anAPI({state, setState})

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

setState 需要是什么样子才能使该测试起作用?

【问题讨论】:

    标签: reactjs unit-testing testing jestjs react-hooks


    【解决方案1】:

    想通了:

    const useApiMock = (api, defaultValue) => {
        let state = defaultValue;
        let setState = updater => {
          if (typeof updater === "function") {
            state = updater(state);
          } else {
            state = updater;
          }
          ref.api = api({ state, setState });
        };
        let ref = {
          api: api({ state, setState })
        };
        return ref;
      };
    

    然后像这样使用:

    const mockApi = useApiMock(someApi, someState)
    
    it("updates name", () => {
        mockApi.api.updateName("new name")
        expect(mockApi.api.name).toEqual("new name")
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-17
      • 2018-11-15
      • 2021-08-26
      • 1970-01-01
      • 2020-04-06
      • 1970-01-01
      • 2019-09-03
      • 1970-01-01
      相关资源
      最近更新 更多