【问题标题】:Moxios always retuning empty when using thunk and axios使用 thunk 和 axios 时 Moxios 总是重新调空
【发布时间】:2020-01-02 18:26:39
【问题描述】:

我一直在尝试模拟总是返回空的 axios 函数:

登录操作:

export function loginUser(email, password) {
  return function(dispatch) {
    return axios
      .post(`${API_URL}/users/authenticate`, { email, password }, { withCredentials: true })
      .then(response => {
          localStorage.setItem("token", JSON.stringify(response.data.user.id));
          dispatch(setupUser(response.data.user.id));
          dispatch({ type: AUTH_USER });
          dispatch({ type: CLEAR_LOGIN_MESSAGE });
      });
  };
}

测试:

describe("async actions", () => {
  beforeEach(() => {
    moxios.install();
  });
  afterEach(() => {
    moxios.uninstall();
  });

  it("logs in", () => {
    moxios.wait(() => {
      const request = moxios.requests.mostRecent();
      request.respondWith({
        status: 200,
        response: {name:"Jill", id:1},
      });
    });

    const expectedActions = [
      { type: AUTH_USER },
      { type: CLEAR_LOGIN_MESSAGE },
      { type: SET_UP_USER, information: {name:"Jill, id:1} },
      { type: REFRESH_DASHBOARD, dashboard: "" },
    ];

    const store = mockStore({});
    return store.dispatch(loginUser({email:"test", password:"test"})).then(() => {
      expect(store.getActions()).toEqual(expectedActions);
    });
  });
});

我明白了:

expect(received).toEqual(expected) // deep equality

- Expected
+ Received

- Array [
-   Object {
-     "type": "AUTH_USER",
-   },
-   Object {
-     "type": "CLEAR_LOGIN_MESSAGE",
-   },
-   Object {
-     "information": 
-       "id": "1",
-       "name": "Jill",
-     },
-     "type": "SET_UP_USER",
-   },
-   Object {
-     "dashboard": "",
-     "type": "CLEAR_DASHBOARD",
-   },
- ]
+ Array []

为什么received返回空?

【问题讨论】:

    标签: reactjs jestjs axios thunk moxios


    【解决方案1】:

    您在调度中写道

    loginUser({email:"test", password:"test"})
    

    但是您的操作不需要对象,它需要 2 个参数

    export function loginUser(email, password) {
    

    我是这样称呼它的:

    loginUser("test", "test")
    
    

    希望有人觉得这很有用

    【讨论】:

      猜你喜欢
      • 2018-02-21
      • 2020-02-04
      • 2021-08-15
      • 2018-09-27
      • 2021-09-20
      • 2018-09-07
      • 1970-01-01
      • 2018-12-02
      • 2021-11-24
      相关资源
      最近更新 更多