测试中测试链式承诺

测试中测试链式承诺

本文介绍了如何在 Jest 测试中测试链式承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面我对我的登录操作进行了测试.我正在模拟 Firebase 函数并想测试是否调用了 signIn/signOut 函数.

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

it('signIn 应该调用 firebase', () => {常量用户 = {电子邮件:'[email protected]',密码:'abd123'};console.log('111');return store.dispatch(signIn(user.email, user.password)).then(() => {console.log('222');//达不到期望(mockFirebaseService).toHaveBeenCalled();});console.log('333');});

● 登录操作 › 登录应调用 Firebase

类型错误:auth.signInWithEmailAndPassword 不是函数

正在测试的操作

//登录动作export const signIn = (email, password, redirectUrl = ROUTEPATH_DEFAULT_PAGE) =>(调度) =>{dispatch({ type: USER_LOGIN_PENDING });返回火力基地.then(auth => auth.signInWithEmailAndPassword(email, password)).catch((e) => {console.error('actions/Login/signIn', e);//注册一个新用户if (e.code === LOGIN_USER_NOT_FOUND) {调度(推(ROUTEPATH_FORBIDDEN));dispatch(toggleNotification(true, e.message, 'error'));} 别的 {dispatch(displayError(true, e.message));setTimeout(() => {调度(显示错误(假,''));}, 5000);扔e;}}).then(res => res.getIdToken()).then((idToken) => {如果(!idToken){dispatch(displayError(true, '对不起,获取令牌时出现问题.'));}调度(onCheckAuth(电子邮件));调度(推送(重定向网址));});};

全面测试

 import configureMockStore from 'redux-mock-store';从redux-thunk"导入 thunk;//登录操作进口 {//onCheckAuth,登入,登出来自'动作';进口 {//USER_ON_LOGGED_IN,USER_ON_LOGGED_OUT来自'actionTypes';//字符串常量//导入 { LOGIN_USER_NOT_FOUND } from 'copy';const 中间件 = [thunk];const mockStore = configureMockStore(middlewares);//模拟模块中的所有导出.函数 mockFirebaseService() {return new Promise(resolve => resolve(true));}//由于services/firebase"是对我们正在测试的这个文件的依赖,//我们需要模拟子依赖项.jest.mock('services/firebase', () => new Promise(resolve => resolve(true)));描述('登录操作',()=> {让商店;beforeEach(() => {store = mockStore({});});it('signIn 应该调用 firebase', () => {常量用户 = {电子邮件:'[email protected]',密码:'abd123'};console.log('111');return store.dispatch(signIn(user.email, user.password)).then(() => {console.log('222');//没有到达期望(mockFirebaseService).toHaveBeenCalled();});console.log('333');});it('signOut 应该调用 firebase', () => {console.log('signOut 应该调用 firebasew');store.dispatch(signOut()).then(() => {期望(mockFirebaseService).toHaveBeenCalled();console.log('store ==>', store);期望(store.getActions()).toEqual({类型:USER_ON_LOGGED_OUT});});console.log('END');});});
解决方案

这里有两个问题,

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

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

it('signOut 应该调用 firebase', () => {console.log('signOut 应该调用 firebasew');return store.dispatch(signOut()).then(() => {//注意我们返回了 promise期望(mockFirebaseService).toHaveBeenCalled();console.log('store ==>', store);期望(store.getActions()).toEqual({类型:USER_ON_LOGGED_OUT});console.log('END');});});

您可以在 Redux 官方文档中找到示例.

其次,您的登录测试失败,因为您模拟了错误的 firebase:

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

那应该看起来更像:

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

Below I have a test for my login actions. I'm mocking a Firebase function and want to test if the signIn/signOut functions are called.

The tests pass. However, I do not see my second console log. Which is this line console.log('store ==>', store);.

it('signIn should call firebase', () => {
  const user = {
    email: '[email protected]',
    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');
});

Action being tested

// 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));
    });
};

Full Test

    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: '[email protected]',
      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');
  });
});
解决方案

You have two issues here,

That is because the test is not waiting for the promise to fulfill, so you should return it:

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');
    });

  });

You can find examples in the Redux official documentation.

Secondly, your signIn test is failing because you have mocked the wrong firebase:

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

That should probably look more like:

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

这篇关于如何在 Jest 测试中测试链式承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 05:15