【问题标题】:React Jest Enzyme testing functionReact Jest Enzyme 测试功能
【发布时间】:2021-08-22 03:03:43
【问题描述】:

我还在学习反应测试。你能告诉我如何测试这个吗?我有这样的,但没有工作。我在下面添加了减速器。

export const getUserData = (data) => async (dispatch, getState) => {
    const user = await fetch(`${process.env.REACT_APP_API_URL}/users/${data}`).then(res => res.json())
    await dispatch(getUser(user))
    return user
}


import { getUserData } from "../userReducers";

global.fetch = jest.fn(() =>
    Promise.resolve({
        json: () => ({ login: 'Someone' })
    })
)

describe("Testing user reducers", () => {
    it("will hit mock API and get response", () => {
        const response = getUserData('Someone')
        expect(response).toEqual({ login: 'Someone' })
    })
})

export const GET_USER = "GET_USER";

export const getUser = (user) => ({
    type: GET_USER,
    payload: user,
});


【问题讨论】:

  • 您是要测试减速器,还是专门测试动作创建器?
  • 我想测试一个减速器@DrewReese
  • 您能否更新您的问题以包含您想练习的减速器功能?
  • 我在那里添加了一个调度功能。 @DrewReese
  • reducer 函数具有类似(state, action) => nextState 的函数签名。为了测试你调用 reducer 函数并传递一些测试状态和调用动作创建者的结果。断言“nextState”是您期望的值。

标签: reactjs jestjs enzyme


【解决方案1】:

你可以像这样使用async/await

it("will hit mock API and get response", async () => {
    const dispatch = mock.fn();
    const getState = mock.fn();
    const response = await getUserData('Someone')(dispatch,  getState);
    expect(response).toEqual({ login: 'Someone' })
    expect(dispatch).toHaveBeenCalled();
})

【讨论】:

  • 顺便说一句,如果我在 reducer 中有一个 dispatch,如何 export const getUserData = (data) => async (dispatch, getState) => { const user = await fetch(${process.env.REACT_APP_API_URL}/users/${data}) .then(res => res.json()) await dispatch(getUser(user)) return user }
  • TypeError: dispatch 不是一个函数。当我尝试添加调度时,我得到了这个。
  • 你可以模拟dispatch并测试它是否被调用
  • 你有什么参考来做一个调度模拟吗?
  • 我先试试看,有问题再问你。
猜你喜欢
  • 1970-01-01
  • 2019-01-29
  • 2019-07-22
  • 2019-07-26
  • 1970-01-01
  • 2017-02-12
  • 2020-08-07
  • 2017-11-26
  • 2019-06-16
相关资源
最近更新 更多