如何在开玩笑测试中测试链式承诺?

时间:2018-01-26 19:31:21

标签: javascript reactjs unit-testing jestjs

下面我对我的登录操作进行了测试。我正在嘲笑firebase函数,并想测试是否调用了signIn / signOut函数。

测试通过然而我没有看到我的第二个控制台日志。这一行是console.log('store ==>', store);

it('signIn should call firebase', () => {
  const user = {
    email: 'first.last@yum.com',
    password: 'abd123'
  };

  console.log('111');
  return store.dispatch(signIn(user.email, user.password)).then(() => {
    console.log('222'); // does not reach
    expect(mockFirebaseService).toHaveBeenCalled();
  });
  console.log('333');
});
  

●登录操作> signIn应该调用firebase

     

TypeError:auth.signInWithEmailAndPassword不是函数

enter image description here

正在测试的行动

// Sign in action
export const signIn = (email, password, redirectUrl = ROUTEPATH_DEFAULT_PAGE) => (dispatch) => {
  dispatch({ type: USER_LOGIN_PENDING });

  return firebase
    .then(auth => auth.signInWithEmailAndPassword(email, password))
    .catch((e) => {
      console.error('actions/Login/signIn', e);
      // Register a new user
      if (e.code === LOGIN_USER_NOT_FOUND) {
        dispatch(push(ROUTEPATH_FORBIDDEN));
        dispatch(toggleNotification(true, e.message, 'error'));
      } else {
        dispatch(displayError(true, e.message));
        setTimeout(() => {
          dispatch(displayError(false, ''));
        }, 5000);
        throw e;
      }
    })
    .then(res => res.getIdToken())
    .then((idToken) => {
      if (!idToken) {
        dispatch(displayError(true, 'Sorry, there was an issue with getting your token.'));
      }

      dispatch(onCheckAuth(email));
      dispatch(push(redirectUrl));
    });
};

完整测试

    import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';

// Login Actions
import {
  // onCheckAuth,
  signIn,
  signOut
} from 'actions';

import {
  // USER_ON_LOGGED_IN,
  USER_ON_LOGGED_OUT
} from 'actionTypes';

// String Constants
// import { LOGIN_USER_NOT_FOUND } from 'copy';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

// Mock all the exports in the module.
function mockFirebaseService() {
  return new Promise(resolve => resolve(true));
}

// Since "services/firebase" is a dependency on this file that we are testing,
// we need to mock the child dependency.
jest.mock('services/firebase', () => new Promise(resolve => resolve(true)));

describe('login actions', () => {
  let store;

  beforeEach(() => {
    store = mockStore({});
  });

  it('signIn should call firebase', () => {
    const user = {
      email: 'first.last@yum.com',
      password: 'abd123'
    };

    console.log('111');
    return store.dispatch(signIn(user.email, user.password)).then(() => {
      console.log('222'); // does not reach
      expect(mockFirebaseService).toHaveBeenCalled();
    });
    console.log('333');
  });

  it('signOut should call firebase', () => {
    console.log('signOut should call firebasew');
    store.dispatch(signOut()).then(() => {
      expect(mockFirebaseService).toHaveBeenCalled();
      console.log('store ==>', store);
      expect(store.getActions()).toEqual({
        type: USER_ON_LOGGED_OUT
      });
    });
    console.log('END');
  });
});

2 个答案:

答案 0 :(得分:5)

这里有2个问题,

  

测试通过然而我没有看到我的第二个控制台日志。这是什么   line console.log('store ==>',store);。

那是因为测试不是在等待履行承诺,所以你应该把它归还:

it('signOut should call firebase', () => {
    console.log('signOut should call firebasew');
    return store.dispatch(signOut()).then(() => { // NOTE we return the promise
      expect(mockFirebaseService).toHaveBeenCalled();
      console.log('store ==>', store);
      expect(store.getActions()).toEqual({
        type: USER_ON_LOGGED_OUT
      });
      console.log('END');
    });

  });

您可以在redux official docs中找到示例。

其次,你的signIn测试失败了,因为你已经模拟了错误的firebase:

jest.mock('services/firebase', () => new Promise(resolve => resolve(true)));

这可能看起来更像是:

jest.mock('services/firebase', () => new Promise(resolve => resolve({
    signInWithEmailAndPassword: () => { return { getIdToken: () => '123'; } }
})));

答案 1 :(得分:1)

  

登录操作> signIn应该调用firebase

     

TypeError:auth.signInWithEmailAndPassword不是函数

这表示您的store.dispatch(signIn(user.email, user.password))失败,因此您的第二个console.log不会进入您的then链,而是使用catchthen的第二个回调参数。