如何用笑话在Redux中模拟异步动作创建者

时间:2019-04-23 13:58:44

标签: javascript reactjs unit-testing redux jestjs

我正在尝试使用玩笑为redux异步动作创建者编写单元测试。

asyncActions.js:

const startSignInRequest = () => ({
  type: START_SIGNIN_REQUEST
});

// action creator to dispatch the success of sign In
export const signInSucceded = user => ({
  type: SIGNIN_USER_SUCCEEDED,
  user
});

// action creator to dispatch the failure of the signIn request
export const signInFailed = error => ({
  type: SIGNIN_USER_FAILED,
  error
});

const signInUser = user => dispatch => {
dispatch(startSignInRequest);
  return signInApi(user).then(
    response => {
      const { username, token } = response.data;
      dispatch(signInSucceded(username));
      localStorage.setItem("token", token);
      history.push("/homepage");
    },
    error => {
      let errorMessage = "Internal Server Error";
      if (error.response) {
        errorMessage = error.response.data;
      }
      dispatch(signInFailed(errorMessage));
      dispatch(errorAlert(errorMessage));
    }
  );
};

signInApi.js:

import axios from "axios";
import { url } from "../../env/config";

const signInApi = async user => {
  const fetchedUser = await axios.post(`${url}/signIn`, {
    email: user.email,
    password: user.password
  });
  return fetchedUser;
};

在redux官方文档的Writing tests中,他们使用fetch-mock库。但是,我认为该库称为真正的Api。 我尝试使用jest mocks模拟axios api。

/ __ mocks / signInApi.js:

const users = [
{
    login: 'user 1',
    password: 'password'
}
];

  export default function signInApi(user) {
    return new Promise((resolve, reject) => {
      const userFound = users.find(u => u.login === user.login);
      process.nextTick(() =>
        userFound
          ? resolve(userFound)
          // eslint-disable-next-line prefer-promise-reject-errors
          : reject({
              error: 'Invalid user credentials',
            }),
      );
    });
  }

__ tests / asyncActions.js:

jest.mock('../axiosApis/signInApi');
import * as actions from '../actions/asyncActions';

describe('Async action creators', async () => {
it('Should create SIGN_IN_USER_SUCCEEDED when signIn user has been done', () => {
    const user = {
                    login: 'user 1',
                    password: 'password'
                }
    await expect(actions.signInUser(user)).resolves.toEqual({
        user
    })
})
});

测试失败,我得到了:

expect(received).resolves.toEqual()

Matcher error: received value must be a promise

Received has type:  function
Received has value: [Function anonymous]

我怎么只能用玩笑来嘲笑这个异步动作创建者?

2 个答案:

答案 0 :(得分:0)

编辑:我必须编辑我的答案,因为第一个答案指向错误的方向。

因此,根据我的理解,您想模拟Action + Return值。在您的情况下,我将立即返回您的模拟函数的结果。因为您没有嘲笑axios.post,所以不需要将所有内容包装在promise中并返回它。您不仅在嘲笑HTTP调用,还在嘲笑整个操作。

const users = [
{
    login: 'user 1',
    password: 'password'
}
];

  export default function signInApi(user) {
    const userFound = users.find(u => u.login === user.login);
    return (userFound ? userFound : {
      error: 'Invalid user'
    });
  }

答案 1 :(得分:0)

看起来您需要更新您的模拟才能解析为这样的对象:

export default function signInApi(user) {
  return new Promise((resolve, reject) => {
    const userFound = users.find(u => u.login === user.login);
    process.nextTick(() =>
      userFound
        ? resolve({  // <= resolve to an object
          data: {
            username: 'the username',
            token: 'the token'
          }
        })
        // eslint-disable-next-line prefer-promise-reject-errors
        : reject({
          error: 'Invalid user credentials',
        }),
    );
  });
}

...然后您真正要测试的是actions.signInUser返回一个函数,可以使用user ...

对其进行调用。

...然后返回另一个函数,可以使用dispatch来调用该函数,以调度适当的操作:

jest.mock('./signInApi');
import * as actions from './asyncActions';

describe('Async action creators', () => {
  it('Should create SIGN_IN_USER_SUCCEEDED when signIn user has been done', async () => {
    const user = {
      login: 'user 1',
      password: 'password'
    };
    const dispatch = jest.fn();
    await actions.signInUser(user)(dispatch);  // <= call the function on a user, then call the resulting function on a dispatch
    expect(dispatch).toHaveBeenCalledTimes(2);  // Success!
    expect(dispatch).toHaveBeenNthCalledWith(1, { type: START_SIGNIN_REQUEST });  // Success!
    expect(dispatch).toHaveBeenNthCalledWith(2, { type: SIGNIN_USER_SUCCEEDED, user: 'the username' });  // Success!
  })
});
相关问题