我已经构建了一个我想测试的react组件api。出于测试目的,api独立于react useState钩子。因此,我的api是从我创建的一个名为useAPI:的自定义钩子中获得的feed-state和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需要什么样子才能使此测试正常工作?
想好了:
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")
})